原题链接:Leetcode 217. Contains Duplicate
Given an integer array nums
, return true
if any value appears at least twice in the array, and return false
if every element is distinct.
Example 1:
Input: nums = [1,2,3,1]
Output: true
Example 2:
Input: nums = [1,2,3,4]
Output: false
Example 3:
Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true
Constraints:
- 1 <= nums.length <= 105
- -109 <= nums[i] <= 109
方法一:哈希表
思路:
遍历数据中的元素,如果它已经在哈希表中,就返回true,否则就将它插入哈希表
c++代码:
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_set<int> s;
for (auto n : nums){
if(s.find(n) != s.end())
return true;
else
s.insert(n);
}
return false;
}
};
复杂度分析:
- 时间复杂度:O(n),n个元素
- 空间复杂度:O(n),需要一个哈希表,长度最大为n
方法二:排序
思路:
对数组进行排序,遍历判断是否和相邻元素相同
c++代码:
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
sort(nums.begin(), nums.end());
for(int i = 0; i < nums.size() - 1; i ++ ){
if(nums[i] == nums[i + 1]) return true;
}
return false;
}
};
复杂度分析:
- 时间复杂度:O(nlogn) 时间开销主要在sort(),sort采用的是改进快速排序,复杂度为O(nlogn)
- 空间复杂度:O(logn),同理,快速排序的空间复杂度为O(logn)