![](/img/trans.png)
[英]O(n) algorithm to find the odd-number-out in array of consecutive integers from 1 to n(not odd numbers)
[英]Given an array of +ve integers, Find the number which occurs odd number of times 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));
}
方法1:通过对数组中的所有元素进行异或运算
我正在尝试X-或所有元素。 那是
正确的方法? 上面是使用X-OR的代码
方法2:使用HashMap如果使用hashmap,则空间复杂度将为O(n)。 哪个不好
我应该使用哪种方法?
此问题假定只有一个数字出现
数组中的次数。 如果您有更多这样的数字-说出其中的K个: a1, a2, ... aK
,
然后在循环结束时,在res
您将获得此值。
res == a1 ^ a2 ^ ... ^ aK
根据该值,您无法推断/提取所有K个未知数a1, a2, ... aK
。
Buf ...您看到的是,如果K = 1(即,如果您正好有一个数字出现
奇数次),最后您将获得该数字的res
。
只要您了解它的工作原理,就可以使用第一种方法。
同样,在第二种方法中,空间不是O(n)
而是O(s)
,
其中s
是数组中不同值的计数。 和你一样
我们可以肯定地说只有1个数字出现了奇数次
那2*s + 1 <= n
即s <= (n-1)/2
。 所以空间复杂
在第二种方法中为O((n-1)/2)
。 当您使用数组时就可以实现
看起来像这样: s
数字出现两次,而1
数字出现一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.