題目
Given a non-empty 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?
你的算法應該具有線性時間複雜度。 你可以不使用額外空間來實現嗎?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
解析
主要思路:
利用XOR異或運算的運算性質a^0 = a, a^b^b = a, a^b = b^a
,對原始數組中的所有數進行異或求和,由於只有待查找數出現1次,而其他數出現2次,因此異或求和的值即爲待查找數
代碼
class Solution {
public int singleNumber(int[] nums) {
int xorSum = 0;
// 遍歷原始數組,進行異或求和
for(int num:nums){
xorSum ^= num;
}
// 返回異或之和
return xorSum;
}
}
推廣
類似於這種,求多個數中的某個或某幾個特殊數時,可以多嘗試使用異或運算的方式進行求解