Link: https://oj.leetcode.com/problems/single-number-ii/
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
我的思路:remember 應該用位操作。對於出現三次的元素,對應的位一定出現3次(還是3的倍數?)。每一位對3取餘,不爲0的位組合起來就是隻出現1次的數。
但我不知道通過什麼操作才能把一個數表示成二進制。//(A[j]>>i) & 1
Note: 沒法下筆。再做。
Time: O(n), Space: O(1) (O(32)
public class Solution {
public int singleNumber(int[] A) {
int[] count = new int[32];//store the total # of ones on each digit
for(int i = 0; i < 32; i++){//for each digit
for(int j = 0; j < A.length; j++){
count[i] += (A[j]>>i) & 1;
}
}
int result = 0;
for(int i = 0; i < 32; i++){
result += (count[i] %3) <<i;//can also use "|="
}
return result;
}
}