一.解法
https://leetcode-cn.com/problems/contains-duplicate/
要点:hashmap
用暴力双循环法会超时,因为复杂度为。
Python,C++,Java都用了相同的哈希表法。
遇到没遇过的值就加入哈希表,如果发现已经加入过,说明重复。
java中还能用hashset代替hashmap。
二.Python实现
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
hashmap = {}
length=len(nums)
for i in range(0,length):
if hashmap.get(nums[i])!=None:
return True;
hashmap[nums[i]] = 1
return False
三.C++实现
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_map<int,int> hashmap;
int length=nums.size();
for(int i=0;i<length;i++){
if(hashmap[nums[i]]) return true;
else{
hashmap[nums[i]]=1;
}
}
return false;
}
};
四.java实现
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> set = new HashSet<>(nums.length);
for (int x: nums) {
if (set.contains(x)) return true;
set.add(x);
}
return false;
}
}