Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
找到數組中只出現一次的數,思路比較簡單,就是利用HashMap記錄每個數字出現的次數,然後遍歷找到出現一次的,可以通過測試
class Solution {
public int singleNumber(int [] nums) {
HashMap<Integer,Integer> map = new HashMap<>();
for (int num : nums) {
if (map.get(num) == null) {
map.put(num, 1);
} else {
map.put(num,map.get(num) + 1);
}
}
for (int num : map.keySet()) {
if (map.get(num) == 1) {
return num;
}
}
return -1;
}
}
下面是一種比較tricky的做法,利用位運算中的異或運算,因爲只有一個數字是出現一次的,其餘的都是成對出現,因爲兩個一樣的數字經過異或操作後得到0,所以我們異或所有數字之後得到0異或那個只出現一次的,因爲0異或任何數字得到的都是本身,所以這樣就得到了只出現一次的數字
解法比較tricky,記住就好了
class Solution {
public int singleNumber(int[] nums) {
int result = 0;
for (int num : nums) {
result ^= num;
}
return result;
}
}