简体   繁体   English

在数组中搜索其他数字,当所有其他数字都相同时,可以使用分治法在O(logn)中完成

[英]Search the different number in array, when all the other numbers are same , can this be done in O(logn) using divide and conquer

假设我们有一个非常大的数组,我们需要找到数组中唯一的不同数,数组中所有其他数字都相同,是否可以使用除法和征服在O(log n)中找到它,就像mergeSort ,请提供一个实现。

This cannot be done in better time complexity than O(n) unless that array is special. 除非该数组是特殊的,否则这样做的时间复杂度不会比O(n)更好。 With the constraints you have given, even if you apply an algorithm like divide and conquer you have to visit every array element at least once. 在给定的约束条件下,即使您应用了诸如分而治之的算法,也必须至少访问每个数组元素一次。

As dividing the array will be O(log n) and comparing 2 elements when array is reduced to size 2 will be O(1) 由于将数组除以O(log n),并且当数组缩小为2时比较2个元素将为O(1)

This is wrongly put. 这是错误地提出的。 Dividing the array is not O(log n). 除数组不是O(log n)。 The reason why something like a binary search works in O(log n) is because the array is sorted and that way you can discard the other half of the array at every step even without looking at what elements they have, thereby halving the size of original problem. 之所以在O(log n)中执行类似二进制搜索的原因,是因为对数组进行了排序,这样您就可以在每一步都丢弃数组的另一半,而无需查看它们具有的元素,从而将数组的大小减半原来的问题。

Intuitively, you can think this as follows : Even if you keep on dividing the array into halves, the leaf nodes of the tree formed are n/2 (Considering you compare 2 elements at leaf). 直观地,您可以这样认为:即使继续将数组划分为两半,形成的树的叶子节点也为n / 2(考虑在叶子上比较2个元素)。 You will have to make n/2 comparisons, which leads to asymptotic complexity of O(n). 您将必须进行n / 2个比较,这会导致O(n)的渐近复杂性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM