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次,找出這個出現一次的數字,要求時間複雜度爲O(n),空間複雜度爲O(1)。最好不傅額外的空間。數組
方法一:考慮所有用二進制表示,若是咱們把 第ith個位置上全部數字的和對3取餘,那麼只會有兩個結果 0 或 1 (根據題意,3個0或3個1相加餘數都爲0). 所以取餘的結果就是那個 「Single Number」。一個直接的實現就是用大小爲 32的數組來記錄全部位上的和。
方法二:使用掩碼變量:
ones 表明第ith位只出現一次的掩碼變量
twos 表明第ith位只出現兩次次的掩碼變量
threes 表明第ith位只出現三次的掩碼變量
當第ith位出現3次時,咱們就ones和twos的第ith位設置爲0. 最終的答案就是 ones。app
算法實現類spa
public class Solution { public int singleNumber(int[] nums) { int[] count = new int[32]; int result = 0; for (int i = 0; i < 32; i++) { for (int n : nums) { // 統計第i位的1的個數 if (((n >> i) & 1) == 1) { count[i]++; } } result |= (count[i] % 3) << i; } return result; } public int singleNumber2(int[] nums) { // 只出現一次的掩碼變量, int ones = 0; // 只出現兩次次的掩碼變量 int twos = 0; // 只出現三次的掩碼變量 int threes; for (int n : nums) { twos |= ones & n; // 異或3次 和 異或 1次的結果是同樣的 ones ^= n; // 對於ones和twos把出現了3次的位置設置爲0(取反以後1的位置爲0) threes = ones & twos; ones &= ~threes; twos &= ~threes; } return ones; } }