classSolution{ publicintsingleNumber(int[] nums){ Map map = new HashMap<>(); for (int x : nums) map.put(x, map.getOrDefault(x, 0) + 1); for (int x : map.keySet()) { if (map.get(x) == 1) return x; } return -1; } }
C++ 代码:
classSolution { public: int
singleNumber(vector<int>& nums){ unordered_map<int, int> map; for (int x : nums) map[x]++; for (constauto& x : map) { if (x.second == 1) return x.first; } return-1; } };
Python 代码:
classSolution: defsingleNumber(self, nums: List[int]) -> int: num_map = defaultdict(int) for x in nums: num_map[x] += 1 for x in num_map: if num_map[x] == 1: return x return-1
TypeScript 代码:
functionsingleNumber(nums: number[]): number{ const numMap: { [key: number]: number } = {}; for (const x of nums) numMap[x] = (numMap[x] || 0) + 1; for (const x in numMap) { if (numMap[parseInt(x)] === 1) returnparseInt(x); } return-1; };