leetcode解题: Contains Duplicate (217)

Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

解法1:Hashtable

很直观的用Hashtable的题,对每一个int记录出现的次数,一但出现多余1则返回true。
C++

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_map<int, int> map;
for (int num: nums) {
++map[num];
if (map[num] > 1) return true;
}
return false;
}
};

Java

1