[英]An array has 2 elements. One element is unique and the other can repeat any number of times. Find the distinct element in < O(n) time
O(n) solution is straight forward. O(n)解决方案很简单。 I can think of something in terms of binary search but that again will be O(n) in worst case as the input array need not be sorted.
我可以从二进制搜索的角度来思考某些问题,但是在最坏的情况下,由于不需要对输入数组进行排序,因此再次将是O(n)。 Is there any solution that runs in O(log n) time?
是否有可以在O(log n)时间内运行的解决方案?
May be one of the solution can be based on divide and conquer techniques. 可能是基于分而治之技术的解决方案之一。
eg Array -> [2,2,2,2,3,2,2] 例如Array-> [2,2,2,2,3,2,2]
Take three variables `First`, `Mid` and `Last`
1. Find `First` first element -> 2 in our case.
2. Find length of array -> 7
3. Find `Mid` element -> 4
4. Sum till `Mid` element -> 2+2+2+2=8 (calculate by Mid * First)
5. If sum from `First` and `Mid` is equal to (`Mid` * `First`) then set `First` as `Mid`+-1 else set `Last` as `Mid`+1
The above method will divide the array to half for each comparision in worst case scenario. 在最坏的情况下,上述方法会将每个比较的数组均分为一半。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.