1. 程式人生 > >Leetcode No.136 ***

Leetcode No.136 ***

return 給定 leet clas col 輸入 turn int class

給定一個非空整數數組,除了某個元素只出現一次以外,其余每個元素均出現兩次。找出那個只出現了一次的元素。

說明:

你的算法應該具有線性時間復雜度。 你可以不使用額外空間來實現嗎?

示例 1:

輸入: [2,2,1]
輸出: 1

示例 2:

輸入: [4,1,2,1,2]
輸出: 4

解答:本題采用異或來計算特別方便。

異或的運算規律:

  1. 交換律:a ^ b ^ c <=> a ^ c ^ b

  2. 任何數於0異或為任何數 0 ^ n => n

  3. 相同的數異或為0: n ^ n => 0

  4. n ^ n => 0

//
136 int singleNumber(vector<int>& nums) { int res=0; for(int i:nums) res ^=i; returnres; }//136

Leetcode No.136 ***