题目链接:https://leetcode.com/problems/contains-duplicate/
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.
思路:使用hash表可以在O(n)的时间内解决
代码如下:
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_map<int, bool> hash;
for(auto val: nums)
{
if(hash.count(val)) return true;
hash[val] = true;
}
return false;
}
};
不得不承认python就是个变态
python
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
return len(nums) != len(set(nums))