Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
your algorithm should have a linear runtime complexity.
could you implement it without using extra memory?
/*
Example1:
Input: [2,2,1]
Output: 1
*/
public class Solution{
public int singleNumber(int[] numbers){
int x = 0;
for(int a : nums){
x ^= a;
}
return x;
}
}
^異或運算
根據二進制運算計算得到結果
比如2是0010,1是0001
那麼抑或就是0011,十進制就是3
這邊0異或2還是2,2異或2得0,也就是說成對出現同樣的數異或之後結果爲0
那麼出現不同的數,就會是最終的結果
時間複雜度是線性的:O(n)
空間複雜度是:O(1)