算法的复杂度(以 O 表示法表示)
谁能告诉我以下算法的复杂度顺序?该算法执行以下操作:
给定一个具有重复数字的未排序整数数组,编写最有效的代码来打印数组中的唯一值。
我也想知道 此实现的硬件使用情况有哪些优点和缺点
private static void IsArrayDuplicated(int[] a)
{
int size = a.Length;
BitArray b = new BitArray(a.Max()+1);
for ( int i = 0; i < size; i++)
{
b.Set(a[i], true);
}
for (int i = 0; i < b.Count; i++)
{
if (b.Get(i))
{
System.Console.WriteLine(i.ToString());
}
}
Console.ReadLine();
}
Can anyone tell me order of complexity of below algorithm? This algorithm is to do following:
Given an unsorted array of integers with duplicate numbers, write the most efficient code to print out unique values in the array.
I would also like to know
What are some pros and cons in the context of hardware usage of this implementation
private static void IsArrayDuplicated(int[] a)
{
int size = a.Length;
BitArray b = new BitArray(a.Max()+1);
for ( int i = 0; i < size; i++)
{
b.Set(a[i], true);
}
for (int i = 0; i < b.Count; i++)
{
if (b.Get(i))
{
System.Console.WriteLine(i.ToString());
}
}
Console.ReadLine();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您有两个
for
循环,一个长度为a.Length
,另一个长度为(如果我正确理解代码)a.Max() + 1
代码>.所以你的算法复杂度是O(a.Length + a.Max())
You have two
for
loops, one of lengtha.Length
and one of length (if I understand the code correctly)a.Max() + 1
. So your algorithmic complexity isO(a.Length + a.Max())
算法的复杂度呈线性。
寻找最大值是线性的。
设置位是线性的。
然而算法也是错误的,
除非你的整数可以被假设为正数。
它也有一个大整数的问题 - 你真的吗
想要分配 MAX_INT/8 字节的内存?
顺便说一句,这个名字让我感到畏缩。 IsXYZ() 应始终返回布尔值。
我想说,再试一次。
更正 - pavpanchekha 有正确答案。
The complexity of the algorithm linear.
Finding the maximum is linear.
Setting the bits is linear.
However the algorithm is also wrong,
unless your integers can be assumed to be positive.
It also has a problem with large integers - do you really
want to allocate MAX_INT/8 bytes of memory?
The name, btw, makes me cringe. IsXYZ() should always return a bool.
I'd say, try again.
Correction - pavpanchekha has the correct answer.
O(n) 可能仅适用于有限/小整数域。每个人都会想到桶排序。哈希映射方法基本上不是 O(n) 而是 O(n^2),因为最坏情况下插入哈希映射的时间复杂度为 O(n) 并且不是常数。
如何在 O(nlog(n)) 中对列表进行排序,然后遍历它并打印重复值。这导致 O(nlog(n)),这可能是问题的真正复杂性。
O(n) is probably only possible for a finite/small domain of integers. Everyone think about bucketsort. The Hashmap approach is basically not O(n) but O(n^2) since worst-case insertion into a hashmap is O(n) and NOT constant.
How about sorting the list in O(nlog(n)) and then going through it and print the duplicate values. This results in O(nlog(n)) which is probably the true complexity of the problem.
您有两个循环,每个循环都基于 n 的大小。我同意鲸鱼的观点,但这应该给你一个良好的开端。
You have two loops, each based on the size of n. I agree with whaley, but that should give you a good start on it.
a.length
上的O(n)
O(n)
ona.length
你的算法的复杂度是 O(N),但算法不正确。
我建议您使用这种方法:
Complexity of your algorithm is O(N), but algorithm is not correct.
I suggest you to use this approach: