第一题是说数组里恰好只有一个元素恰好出现了一次,其他元素都恰好出现了两次。
Given an 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?
要求O(n)的时间复杂度, 并且不使用额外的存储空间
可以利用异或这个操作!事实上,如果其他元素出现的次数都为偶数的话都可以用异或。因为n^n = 0, m^0 = m,而且异或有结合律。
class Solution {
public:
int singleNumber(int A[], int n) {
if(n == 0){
return 0;
}
int result = A[0];
for(int i = 1; i < n; i++){
result = result ^ A[i];
}
return result;
}
};
第二题,第一题是说数组里恰好只有一个元素恰好出现了一次,其他元素都恰好出现了两次。
以下这方法适用于其他元素都恰好出现了2 次或2次以上(设为m)的情况:
将数组(大小为n)的所有元素写成32位二进制,对于每一位,n个值求和再模m,就能得到“落单”的元素那一位是多少,
比如n=7,某一位的7个值为1 1 1 0 1 1 1,那么“落单”的元素那一位是0;若果是0 0 0 1 0 0 0, 那么“落单”的元素那一位是1。
“落单”的元素每一位都知道后,这个元素的值也就知道了。
class Solution {
public:
int singleNumber(int A[], int n) {
int bits[32];
int res = 0;
for(int i = 0; i < 32; i++) {
bits[i] = 0;
for(int j = 0; j < n; j++) {
if((A[j]>>i) & 1) {
bits[i] = (bits[i]+1) % 3; // 模m
}
}
res |= bits[i]<<i;
}
return res;
}
};