1、題目數組
一、審題spa
二、分析code
在線性時間複雜度、常量空間開銷的狀況下統計出一個整形數組中只出現一次的兩個數(其餘的數都是出現2次)。blog
2、解答it
一、思路ast
①、對數組全部元素進行異或(^) 操做,獲得只出現 1 次的這兩個數的異或結果 diff。class
②、diff &= -diff ,獲得只出現一次的兩個數的二進制形式的第一個不一樣的位置 a。遍歷
③、初始化結果數組{0, 0},遍歷數組中的元素,若 a = 1,則與結果數組中第一個元素進行異或;若 a = 0 ,則與第二個元素進行異或。二進制
④、返回結果數組。im
public int[] singleNumber(int[] nums) { // Pass 1 : // Get the XOR of the two numbers we need to find int diff = 0; for(int num: nums) diff ^= num; // Get its last set bit diff &= -diff; // Pass 2 : int[] rets = {0, 0}; for(int num: nums) { if((num & diff) == 0) rets[0] ^= num; else rets[1] ^= num; } return rets; }