简体   繁体   中英

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. 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)

This is wrongly put. Dividing the array is not 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.

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). You will have to make n/2 comparisons, which leads to asymptotic complexity of O(n).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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