136. Single Number數組
Given an array of integers, every element appears twice except for one. Find that single one. (Easy)app
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?spa
分析:code
第一問屬於技巧題,作過就會,沒作過很難想。考慮異或操做,相同數異或以後爲0, 0與一個數異或仍是這個數自己,且異或操做知足交換律和結合律。blog
因此這個題將全部的數異或起來,就能獲得那個落單的數。three
代碼:element
1 class Solution { 2 public: 3 int singleNumber(vector<int>& nums) { 4 int result = 0; 5 for (int i = 0; i < nums.size(); ++i) { 6 result ^= nums[i]; 7 } 8 return result; 9 } 10 };
137. Single Number IIit
Given an array of integers, every element appears three times except for one. Find that single one. (Medium)io
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?ast
分析:
除了「單身狗」之外其餘元素均出現了三次,考慮上一題中的異或的思想(不進位加法,兩個1以後就變成0),推廣到三個數,就是有一位1若是出現三遍,就應該抵消爲0;
因此能夠考慮創建一個32個元素數組表示int的各個位置,而後把每一個數的每一位對應加進去,mod 3後的結果恢復成一個數即爲結果。
代碼:
1 class Solution { 2 public: 3 int singleNumber(vector<int>& nums) { 4 int bitArray[32]; 5 memset(bitArray, 0, sizeof(bitArray)); 6 int result = 0; 7 for (int i = 0; i < 32; ++i) { 8 for (int j = 0; j < nums.size(); ++j) { 9 bitArray[i] += (nums[j] >> i & 1); 10 } 11 bitArray[i] %= 3; 12 result |= (bitArray[i] << i); 13 } 14 return result; 15 } 16 };
260. Single Number III
Given an array of numbers nums
, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. (Medium)
For example:
Given nums = [1, 2, 1, 3, 2, 5]
, return [3, 5]
.
Note:
[5, 3]
is also correct.
分析:
有兩個單身狗,其餘都是出現兩次。考慮怎麼把這個問題轉化爲single number1的問題。
利用1中的思路,先把全部的數異或,最後能夠獲得一個數。能夠知道這個數(xorResult)是那兩個單身狗異或的結果,可是咱們沒法從這個數恢復兩個數自己。
可是咱們能夠xorResult中第一個1出現的位置,這個位置是1說明以前兩個數在這一位不一樣(一個0,一個1);
因而咱們能夠把原數組中的元素這一位是0仍是1分爲兩個數組,這兩個數組便都是single number1的問題,最後把兩個結果添加到vector返回。
代碼:
1 class Solution { 2 public: 3 vector<int> singleNumber(vector<int>& nums) { 4 int xorResult = 0; 5 for (int i = 0; i < nums.size(); ++i) { 6 xorResult ^= nums[i]; 7 } 8 int lastBitofOne = xorResult - (xorResult & (xorResult - 1) ); 9 int result1 = 0, result2 = 0; 10 for (int i = 0; i < nums.size(); ++i) { 11 if ( (nums[i] & lastBitofOne) == 0 ) { 12 result1 ^= nums[i]; 13 } 14 else { 15 result2 ^= nums[i]; 16 } 17 } 18 vector<int> result{result1, result2}; 19 return result; 20 } 21 };