LeetCode 15 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?
分析:ビット演算を考察する.
3つの整数変数を用いて,彼らをバイナリ数と見なし,この3つの数で3進数演算をシミュレートした.
onesは1人あたり1(残り3)に1回格納される場合.
twosは1人あたり1(残り3)を2回保存する場合がある.
onesとtwosのどちらかが1の場合、そのビット1が3回現れたことを説明します.この場合、onesとtwosの対応する位置を0にします.
これで、最後にonesが結果です.
NOTE: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
分析:ビット演算を考察する.
3つの整数変数を用いて,彼らをバイナリ数と見なし,この3つの数で3進数演算をシミュレートした.
onesは1人あたり1(残り3)に1回格納される場合.
twosは1人あたり1(残り3)を2回保存する場合がある.
onesとtwosのどちらかが1の場合、そのビット1が3回現れたことを説明します.この場合、onesとtwosの対応する位置を0にします.
これで、最後にonesが結果です.
public class Solution {
public int singleNumber(int[] A) {
int ones = 0, twos=0, temp = 0;
for(int i=0; i<A.length; i++){
twos = twos | (ones & A[i]);
ones = ones^A[i];
temp = ~(ones & twos);
ones = ones & temp;
twos = twos & temp;
}
return ones;
}
}