給定一個非空整數數組,除了某個元素只出現一次以外,其餘每個元素均出現兩次。找出那個只出現了一次的元素。
說明:
你的算法應該具有線性時間複雜度。 你可以不使用額外空間來實現嗎?
方法 1:哈希表
算法
我們用哈希表避免每次查找元素是否存在需要的 O(n)O(n) 時間。
遍歷 \text{nums}nums 中的每一個元素
查找 hash\_tablehash_table 中是否有當前元素的鍵
如果沒有,將當前元素作爲鍵插入 hash\_tablehash_table
最後, hash\_tablehash_table 中僅有一個元素,用 popitem 獲得它
python
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
hash_table = {}
for i in nums:
try:
hash_table.pop(i)
except:
hash_table[i] = 1
return hash_table.popitem()[0]
class Solution {
public int singleNumber(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
for (Integer i : nums) {
Integer count = map.get(i);
count = count == null ? 1 : ++count;
map.put(i, count);
}
for (Integer i : map.keySet()) {
Integer count = map.get(i);
if (count == 1) {
return i;
}
}
return -1; // can't find it.
}
}
作者:yinyinnie
鏈接:https://leetcode-cn.com/problems/two-sum/solution/xue-suan-fa-jie-guo-xiang-dui-yu-guo-cheng-bu-na-y/
來源:力扣(LeetCode)
方法 2:位操作
概念
如果我們對 0 和二進制位做 XOR 運算,得到的仍然是這個二進制位
a \oplus 0 = aa⊕0=a
如果我們對相同的二進制位做 XOR 運算,返回的結果是 0
a \oplus a = 0a⊕a=0
XOR 滿足交換律和結合律
a \oplus b \oplus a = (a \oplus a) \oplus b = 0 \oplus b = ba⊕b⊕a=(a⊕a)⊕b=0⊕b=b
所以我們只需要將所有的數進行 XOR 操作,得到那個唯一的數字。
python
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a = 0
for i in nums:
a ^= i
return a
java
int ans = nums[0];
if (nums.length > 1) {
for (int i = 1; i < nums.length; i++) {
ans = ans ^ nums[i];
}
}
return ans;
作者:yinyinnie
鏈接:https://leetcode-cn.com/problems/two-sum/solution/xue-suan-fa-jie-guo-xiang-dui-yu-guo-cheng-bu-na-y/
來源:力扣(LeetCode)
作者:LeetCode
鏈接:https://leetcode-cn.com/problems/two-sum/solution/zhi-chu-xian-yi-ci-de-shu-zi-by-leetcode/
來源:力扣(LeetCode)