問題:
Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
給定一個整數數組,每個元素都出現三次,除了一個元素只出現過一次,找到那個單一數。
思路一:不考慮附加條件,可以採用暴力方法,依次對每個算法進行比較
思路二:採用異或的方法
class Solution {
public int singleNumber(int[] nums) {
int a = 0;
int b = 0;
for(int i = 0;i<nums.length;i++){
b = (b^nums[i])&~a;
a = (a^nums[i])&~b;
}
return b;
}
}
對於出現奇數次的該類方法都可以用該方法。