- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
函数在运行大量元素时无法通过性能测试:超出时间限制。 如何通过性能测试?
//Function finds indices of two elements whose sum is equal to as passed in the parameter
public static Tuple<int, int> FindTwoSum(IList<int> list, int sum)
{
for (int i = 0; i < list.Count; i++)
{
int sum2 = sum - list[i];
int index = list.IndexOf(sum2);
if (index > 0 )
{
return new Tuple<int, int>(i, index);
}
}
return null;
}
//Main function to call FindTwoSum method
public static void Main(string[] args)
{
Tuple<int, int> indices = FindTwoSum(new List<int>() { 1, 3, 5, 7, 9 },12);
Console.WriteLine(indices.Item1 + " " + indices.Item2);
}
最佳答案
从表面上看,散列解决方案应该是最快的 - 实际上,它可能适用于大小超过 2GB 的非常大的数组。
然而(令人惊讶的是)对于大小高达 50,000,000 个元素的 int
数组,对数组进行排序并使用适用于已排序数组的优化算法会更快。
这是一个可以在排序数组上使用的算法(请注意,它需要一个额外的数组,该数组仅用于在排序前指示元素的原始索引):
public static Tuple<int, int> FindTwoSumInSortedList(IList<int> list, int[] indices, int sum)
{
for (int i = 0, j = list.Count - 1; i < j;)
{
int s = list[i] + list[j];
if (s == sum)
return new Tuple<int, int>(indices[i], indices[j]);
else if (s < sum)
++i;
else
--j;
}
return null;
}
对原始列表进行排序需要一些额外的工作:
int n = 10000000;
int[] array = new int[n];
...
var indices = Enumerable.Range(0, n).ToArray();
Array.Sort(array, indices);
result = FindTwoSumInSortedList(array, indices, target);
这看起来确实需要大量的额外工作,但令我惊讶的是,它在包含 20,000,000 个元素的数组上的表现优于哈希算法。
我把我的测试程序贴在下面,以供批评。对于 FindTwoSumInSortedList()
算法,我已尝试使样本数据尽可能地难看。
我在 PC 上从 RELEASE 构建中获得的结果是:
n = 10,000,000
3031
(5000000, 5000001)
1292
(5000000, 5000001)
n = 20,000,000
6482
(10000000, 10000001)
2592
(10000000, 10000001)
n = 50,000,000
17408
(25000000, 25000001)
5653
(25000000, 25000001)
所以你可以看到排序算法的速度是原来的两倍多。这真让我吃惊!
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
class Program
{
public static void Main()
{
int n = 10000000;
int[] array = new int[n];
var rng = new Random(18789);
for (int i = 0; i < n; ++i)
array[i] = rng.Next(0, n);
array[n/2] = n;
array[n/2 + 1] = n+1;
var sw = Stopwatch.StartNew();
// This is too slow to test:
//var result = FindTwoSum(array, n*2+1);
//Console.WriteLine(sw.ElapsedMilliseconds);
//Console.WriteLine(result);
sw.Restart();
var result = FindTwoSumFaster(array, n*2 + 1);
Console.WriteLine(sw.ElapsedMilliseconds);
Console.WriteLine(result);
sw.Restart();
var indices = Enumerable.Range(0, n).ToArray();
Array.Sort(array, indices);
result = FindTwoSumInSortedList(array, indices, n*2+1);
Console.WriteLine(sw.ElapsedMilliseconds);
Console.WriteLine(result);
}
public static Tuple<int, int> FindTwoSum(IList<int> list, int sum)
{
for (int i = 0; i < list.Count; i++)
{
int sum2 = sum - list[i];
int index = list.IndexOf(sum2);
if (index > 0)
{
return new Tuple<int, int>(i, index);
}
}
return null;
}
public static Tuple<int, int> FindTwoSumInSortedList(IList<int> list, int[] indices, int sum)
{
for (int i = 0, j = list.Count - 1; i < j;)
{
int s = list[i] + list[j];
if (s == sum)
return new Tuple<int, int>(indices[i], indices[j]);
else if (s < sum)
++i;
else
--j;
}
return null;
}
public static Tuple<int, int> FindTwoSumFaster(IList<int> list, int sum)
{
if (list == null)
throw new NullReferenceException("Null list");
// constructing a hashset to have O(1) operations
var listSet = new HashSet<int>();
// number -> index mapping
// O(n) complexity
var listReverseSet = new Dictionary<int, int>();
int i = 0;
foreach (var elem in list)
{
if (!listSet.Contains(elem))
listSet.Add(elem);
listReverseSet[elem] = i++;
}
// O(n) complexity
int listCount = list.Count;
for (int index = 0; index < listCount; index++)
{
var elem = list[index];
if (listSet.Contains(sum - elem))
return new Tuple<int, int>(index, listReverseSet[sum - elem]);
}
return null;
}
}
}
关于c# - 使用大量元素的列表时超过时间限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36293087/
我使用这个 cmd 应用程序 https://github.com/tokland/youtube-upload 上传 50 个视频后,我收到此错误: [RequestError] Server re
尝试将 docker 容器提交到镜像时出现错误: [root@dockerregistry /]# docker commit da4180ab1536 dockerregistry:5000/myi
我只是想知道这样做会更好吗: if((fd = open(filename, O_RDWR)) == -1) { fprintf(stderr, "open [ %s ]\n", strerror(e
我在我的开发机器(单个笔记本)中使用 Elasticsearch 1.4.4。一切都设置为默认值,因为我从未更改过任何设置。 当我启动它时,我通常会收到以下消息: [2015-10-27 09:38:
我收到错误 Lock wait timeout exceeded;尝试重新启动事务。这是什么原因,如何解决?仅供引用:MySQL 配置文件中的 innodb_lock_wait_timeout = 1
我对 Slack 中的 block 功能有疑问。有人设法构建 3 列而不是 2 列吗? 我凭直觉尝试了以下代码,但它不起作用: { "blocks": [ {
div 中的内容超过由 css 决定的固定大小。 #fixeddiv { position: fixed; margin: auto; max-height: 300px
我想将 EditText 字段限制为 150 个字符,我可以很容易地做到这一点。但是,当用户试图超过该限制时,我还需要通过键入(即第 151 个字符)或粘贴超过 150 个字符来提醒用户。 解决这个问
我目前正在使用此代码并排记录两个窗口: ffmpeg -f gdigrab -framerate 30 -i title="" -f gdigrab -framerate 30 -i title=""
我在几个包含长字符串的单元格上使用嵌套的 SUBSTITUE 函数,并定期更新 SUBSTITUE fx,这导致我将其复制并粘贴到所有需要它的单元格中。问题是,我的 SUBSTITUTE 列表会随着时
我创建了一个标题 div,如下所示:
Here is the demo link 您怎么看,页面中只有 8 个广告可见,但我有 14 个广告。我已阅读有关广告限制的信息 here但不明白是不是我的情况?有人可以给我确切的答案,为什么我看不
我的非常简单的算法 - C 中的快速排序有问题。它非常有效(随机化大约 0.1 秒并检查列表是否已排序)但是当我想要对超过 500k 的元素进行排序时它会崩溃。不幸的是,我需要对它们进行更多排序,因为
我成功解决了一个关于 Hackerrank 的问题,它通过了所有测试用例,但我得到了一个错误,超过了时间限制。我猜如果我优化我的代码它会工作,但我想不出任何方法来使我的代码更有效率。 问题是: 对大小
你会如何用 包围下面的文字3 个反引号 ```使用 tpope 的 Vim Surround . 我所能做的就是 1 个反引号 使用 S`在视觉模式下: 最佳答案 这不是你问的,但这可以在没有环绕的情
我目前有一个模拟账户。我正在尝试为我的雇主使用 SwifType 制作 POC。我们有一个非常大的数据库,每 1 小时索引一次,并创建一个 JSON 文件。我认为与 Elastic 的集成将非常容易,
我为一个大约有 100 到 120 名成员的小型组织维护网站。 每个月,我们都会发送一封电子邮件,通知我们的成员我们将在即将举行的 session 中讨论的主题。 我正在尝试使用我们的网站为我们提供一
这个问题已经有答案了: How to automatically input an array formula as string with more than 255 characters in l
我有一个在 JBoss 6.1 中运行的 JSF 应用程序,它使用内部Tomcat Servlet 容器。 我已经通过apache commons文件上传实现了上传。我想防止上传过大的文件并设置了属性
当我尝试在 PyMySQL 上执行查询时,出现以下错误: pymysql.err.InternalError: (1205, 'Lock wait timeout exceeded; try rest
我是一名优秀的程序员,十分优秀!