
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,記住怎么操作就行了。
然后 這類題目,目前還不想深入介入。
看這個(gè)博文就懂了。
http://www.cnblogs.com/springfor/p/3870863.html
**
總結(jié): bit maniupulation
明天微軟面試, 內(nèi)心其實(shí)很看重,很在乎,所以很緊張。希望好運(yùn)!
希望女朋友的托福成績可以有進(jìn)步!
**
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;
}
}
沒怎么細(xì)想,看答案做了出來。
其實(shí)就是把每個(gè)數(shù)都拆車2為底的多塊。用一個(gè)32位數(shù)組記錄個(gè)數(shù)。然后 % 3,因?yàn)槌霈F(xiàn)三次的數(shù),他們各個(gè)部分的次數(shù)一定是3,可以全部消除。
由此可以想到,如果這個(gè)數(shù)列中,所有數(shù)字都出現(xiàn)了k次,只有一個(gè)數(shù)字只用了一次。
那么就是同樣的方法, % 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