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
原理:x ^ 0 = x,x ^ x = 0