LeetCode217. Contains Duplicate(模拟)
- Easy
- Accepted:302,459
- Submissions:595,526
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.
Example 1:
Input: [1,2,3,1]
Output: true
Example 2:
Input: [1,2,3,4]
Output: false
Example 3:
Input: [1,1,1,3,3,4,3,2,4,2]
Output: true
链接
https://leetcode.com/problems/contains-duplicate/
题意
给定一个数组,判断是否存在相同元素。
题解
- 暴力两层循环,时间复杂度$O(n^2)$
- 先排序然后判断是否存在相邻元素相等,时间复杂度$O(nlogn)$
- 使用哈希,判断是否存在一个元素出现的次数大于1,时间复杂度$O(n)$,多种实现方式
代码
- Runtime: 56 ms, faster than 29.77% of C++ online submissions for Contains Duplicate.
- Memory Usage: 16.5 MB, less than 48.52% of C++ online submissions for Contains Duplicate.
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_set <int> uset;
for (int i = 0; i < nums.size(); ++i)
{
if (uset.find(nums[i]) != uset.end())
return true;
uset.insert(nums[i]);
}
return false;
}
};
还有一种“很骚”的办法,利用集合set的特性。
- Runtime: 40 ms, faster than 75.40% of C++ online submissions for Contains Duplicate.
- Memory Usage: 15.9 MB, less than 64.69% of C++ online submissions for Contains Duplicate.
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
return nums.size() > unordered_set<int>(nums.begin(), nums.end()).size();
}
};
The end.
2019年3月2日 星期六