給定一個非空整數數組,除了某個元素只出現一次之外,其他每一個元素均出現兩次。找出那個只出現了一次的元素。php
說明:你的算法應該具備線性時間複雜度。你能夠不使用額外空間來實現嗎?算法
Given an array of integers, every element appears twice except for one. Find that single one.
Note:數組Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?app
Example 1:
Input: [2,2,1]
Output: 1函數Example 1:
Input: [4,1,2,1,2]
Output: 4code
PHP 的 array_count_values() 函數能夠用於統計數組中全部值出現的次數。返回的結果也是一個數組,key 爲數組中的元素,value 爲該元素出現的次數。element
function singleNumber($nums) { $valueCnt = array_count_values($nums); return array_search(1, $valueCnt) !== false ? array_search(1, $valueCnt) : false; }
設置一個哈希數組,遍歷給定數組的元素,若是該元素不在哈希表裏,就將該元素放入哈希表中,反之,則將該元素從哈希表中移除。最後哈希表剩下的元素確定只有一個,則爲所求解。但這個不知足條件中提到的「不使用額外空間」。
時間複雜度:O(n),空間複雜度:O(n)it
function singleNumber($nums) { $arr = []; foreach ($nums as $num) { if (!in_array($num, $arr)) { $arr[] = $num; } else { array_splice($arr, array_search($num, $arr), 1); } } return $arr[0]; }
這個是看了題解才知道還有這麼簡單的方法!好久沒用「異或」這個位運算符了。io
對 0 和二進制位作 XOR 運算,獲得的仍然是這個二進制位; 對相同的二進制位作 XOR 運算,返回的結果是 0;
時間複雜度:O(1),空間複雜度:O(n)function
function singleNumber($nums) { $ans = 0; foreach ($nums as $num) { $ans = $ans ^ $num; } return $ans; }
運算過程以下: ans = 0,num = 3:0 ^ 3 = 0 ^ 11(二進制) = 11(二進制) = 3(十進制); ans = 3,num = 1:3 ^ 1 = 11(二進制) ^ 1 = 10(二進制) = 2(十進制); ans = 2,num = 1:2 ^ 1 = 10(二進制) ^ 1 = 11(二進制) = 3(十進制); ans = 3,num = 2:3 ^ 2 = 11 ^ 10(二進制) = 01(二進制) = 1(十進制); ans = 1,num = 3:1 ^ 3 = 1 ^ 11(二進制) = 10(二進制) = 2(十進制)。