![](/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.