My code:
public class Solution {
public int singleNumber(int[] nums) {
if (nums == null || nums.length == 0)
return 0;
int[] arr = new int[32];
int ret = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < 32; j++) {
if (((nums[i] >> j) & 1) == 1)
arr[j] += 1;
}
}
for (int i = 0; i < 32; i++) {
if (arr[i] % 3 == 1)
ret += (1 << i);
}
return ret;
}
}
My test result:
這道題目,看了之后就決定看答案了,bit manipulation,記住怎么操作就行了。
然后 這類題目,目前還不想深入介入。
看這個博文就懂了。
http://www.cnblogs.com/springfor/p/3870863.html
**
總結: bit maniupulation
明天微軟面試, 內心其實很看重,很在乎,所以很緊張。希望好運!
希望女朋友的托福成績可以有進步!
**
Anyway, Good luck, Richardo!
My code:
public class Solution {
public int singleNumber(int[] nums) {
if (nums == null || nums.length == 0)
return -1;
int[] count = new int[32];
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < 32; j++) {
if (((nums[i] >> j) & 1) == 1) {
count[j] += 1;
count[j] = count[j] % 3;
}
}
}
int base = 1;
int ret = 0;
for (int i = 0; i < 32; i++) {
ret += count[i] * base;
base *= 2;
}
return ret;
}
}
沒怎么細想,看答案做了出來。
其實就是把每個數都拆車2為底的多塊。用一個32位數組記錄個數。然后 % 3,因為出現三次的數,他們各個部分的次數一定是3,可以全部消除。
由此可以想到,如果這個數列中,所有數字都出現了k次,只有一個數字只用了一次。
那么就是同樣的方法, % k
累,晚安。
Anyway, Good luck, Richardo!
My code:
public class Solution {
public int singleNumber(int[] nums) {
if (nums == null || nums.length == 0) {
return -1;
}
int[] bits = new int[32];
for (int i = 0; i < nums.length; i++) {
int temp = nums[i];
for (int j = 31; j >= 0; j--) {
if ((temp & 1) == 1) {
bits[j]++;
}
temp = (temp >> 1);
}
}
int ret = 0;
int base = 1;
for (int i = 31; i >= 0; i--) {
ret += (bits[i] % 3) * base;
base *= 2;
}
return ret;
}
}
沒想到直接做了出來。還是記得思路吧。。。
Anyway, Good luck, Richardo! 08/05/2016