public class Solution { public int SingleNumber(int[] nums) { Dictionary<int, int> dic = new Dictionary<int, int>(); foreach (var n in nums) { if (!dic.ContainsKey(n)) { dic.Add(n, 1); } else { dic[n]++; } } var result = 0; foreach (var d in dic) { if (d.Value == 1) { result = d.Key; } } //Console.WriteLine(result); return result; } }
https://leetcode.com/problems/single-number/#/description
C++代码:
class Solution { public: int singleNumber(vector<int>& nums) { set<int> SET; for (auto n : nums) { if (SET.find(n) == SET.end()) { SET.insert(n); } else { SET.erase(n); } } for (auto s : SET) { return s; } } };
补充一个python的实现:
1 class Solution: 2 def singleNumber(self, nums: 'List[int]') -> int: 3 a = 0 4 for i in nums: 5 a ^= i 6 return a
分析:利用位运算的两个性质:
性质1:
1 ^ 0 = 1
0 ^ 0 = 0
因此
x ^ 0 = x
性质2:
1 ^ 1 = 0
0 ^ 0 = 0
因此
x ^ x = 0
异或运算是符合"交换律"和"结合律"的,可以理解为实数的加法
也就是说,对于nums=[4,1,2,1,2]有:
0 ^ 4 ^ 1 ^ 2 ^ 1 ^ 2
等价于
0 ^ 4 ^ (1 ^ 1) ^ (2 ^ 2)
等价于(利用性质1,将1^1计算出来,将2^2计算出来)
0 ^ 4 ^ 0 ^ 0
等价于
0 ^ 4
等于(利用性质2)
4
而这正好就是在nums中只出现过一次的数字
Java版本:
1 class Solution { 2 public int singleNumber(int[] nums) { 3 int base = 0; 4 int l = nums.length; 5 for(int i=0;i<l;i++){ 6 base = base ^ nums[i]; 7 } 8 return base; 9 } 10 }