[英]Given an array of +ve integers, Find the number which occurs odd number of times in O(n) time & constant space.
Given an array of positive integers. 给定一个正整数数组。 All numbers occur even number of times except one number which occurs odd number of times.
所有数字均出现偶数次,但一个数字出现奇数次。 Find the number in O(n) time & constant space.
在O(n)时间和恒定空间中找到数字。
int getOddOccurrence ( int ar[]){
int i;
int res = 0;
for (i = 0; i < ar.size; i++)
res = res ^ ar[i];
return res;
}
/* Diver function to test above function */
PSVM() {
int ar[] = {2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2};
SOP(getOddOccurrence(ar));
}
Approach 1: By X-OR ing all the elements in an array 方法1:通过对数组中的所有元素进行异或运算
I am trying to x-or all the elements. 我正在尝试X-或所有元素。 Is that the
那是
correct approach? 正确的方法? Above is the code using X-OR
上面是使用X-OR的代码
Approach 2: By using HashMap If I use hashmap , the space complexity would be O(n). 方法2:使用HashMap如果使用hashmap,则空间复杂度将为O(n)。 Which is not good.
哪个不好
Which approach should I use? 我应该使用哪种方法?
This problem assumes there is only one number which occurs odd number of 此问题假定只有一个数字出现
times in the array. 数组中的次数。 If you have more such numbers - say K of them:
a1, a2, ... aK
, 如果您有更多这样的数字-说出其中的K个:
a1, a2, ... aK
,
then at the end of the loop, in res
you will get this value. 然后在循环结束时,在
res
您将获得此值。
res == a1 ^ a2 ^ ... ^ aK
From that value you cannot infer/extract all K unknown numbers a1, a2, ... aK
. 根据该值,您无法推断/提取所有K个未知数
a1, a2, ... aK
。
Buf ... you see, if K=1 (ie if you have exactly one number occurring Buf ...您看到的是,如果K = 1(即,如果您正好有一个数字出现
odd number of times), at the end you will get in res
just that number. 奇数次),最后您将获得该数字的
res
。
Use the first approach as long as you understand why it works. 只要您了解它的工作原理,就可以使用第一种方法。
Also, in the second approach the space is not O(n)
but O(s)
, 同样,在第二种方法中,空间不是
O(n)
而是O(s)
,
where s
is the count of distinct values in your array. 其中
s
是数组中不同值的计数。 And as you 和你一样
have only 1 number occurring odd number of times we can say for sure 我们可以肯定地说只有1个数字出现了奇数次
that 2*s + 1 <= n
ie s <= (n-1)/2
. 那
2*s + 1 <= n
即s <= (n-1)/2
。 So the space complexity 所以空间复杂
is O((n-1)/2)
in the second approach. 在第二种方法中为
O((n-1)/2)
。 You achieve it when your array 当您使用数组时就可以实现
looks like this: s
numbers occurring twice, and 1
number occurring once. 看起来像这样:
s
数字出现两次,而1
数字出现一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.