简体   繁体   English

一个数组有2个元素。 一个元素是唯一的,另一个元素可以重复任意多次。 在<O(n)时间内找到不同的元素

[英]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.

相关问题 如何在 O(n) 时间和 O(n) 空间中找到重复 (n/3) 次大小为 n 的数组的数字? - How to find a number that was repeated (n/3) times an array of size n, in O(n) time and O(n) space? 有一个n个数字的数组。 一个数字重复n / 2次,其他n / 2个数字不同 - There is an array of n numbers. One number is repeated n/2 times and other n/2 numbers are distinct 我们可以找到线性时间复杂度 O(n) 的数组中每个元素的等级吗? - Can we find rank of each element in array with Linear Time Complexity O(n)? 在O(n)时间内估计阵列元素的频率 - Estimating frequency of element of an array in O(n) time 将数组元素平方为O(n)运行时间 - square the array element in O(n) running time 从 n 个元素的数组中找出形成元素 K 的方法数 - Find the number of ways to form an element K from an array of n elements 在 O(n * log n) 时间内找到 Array 中加起来等于目标数的两个元素 - Find Two elements in the Array that add up to the Target number in O(n * log n) Time 如何在一个元素为零的数组中查找元素数 - How to find number of elements in an array which has one of its element as zero 用 O(n) 用整个数组中所有其他元素的倍数替换数组元素 - Replace the array element with the multiples of all other elements throughout the array with O(n) 在数组中重复N次 - Repeat a Number N Times in an Array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM