只出現一次的數字
給定一個非空整數數組,除了某個元素只出現一次以外,其餘每個元素均出現兩次。找出那個只出現了一次的元素。
說明:你的算法應該具有線性時間複雜度。 你可以不使用額外空間來實現嗎?
-
示例 1:
輸入: [2,2,1]
輸出: 1 -
示例 2:
輸入: [4,1,2,1,2]
輸出: 4
class Solution {
public int singleNumber(int[] nums) {
int res = nums[0];
for(int i = 1; i < nums.length; i++){
res = nums[i] ^ res;
}
return res;
}
}
只出現一次的數字 II
給定一個非空整數數組,除了某個元素只出現一次以外,其餘每個元素均出現了三次。找出那個只出現了一次的元素。
說明:你的算法應該具有線性時間複雜度。 你可以不使用額外空間來實現嗎?
-
示例 1:
輸入: [2,2,3,2]
輸出: 3 -
示例 2:
輸入: [0,1,0,1,0,1,99]
輸出: 99
class Solution {
public int singleNumber(int[] nums) {
//考察位運算:找出只出現一次的數字
//設計一個運算器,使得該數字出現3次時置零,其餘的返回本身
//x & ~x = 0; x & ~0 = x;
int one = 0;
int two = 0;
int three = 0;
for(int num : nums){
// two的相應的位等於1,表示該位出現2次
two |= (one & num);
// one的相應的位等於1,表示該位出現1次
one ^= num;
// three的相應的位等於1,表示該位出現3次
three = (one & two);
// 如果相應的位出現3次,則該位重置爲0
two &= ~three;
one &= ~three;
}
return one;
}
}