0%

[Leetcode]217. 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.

例子

Input: [1,2,3,1]
Output: true

解题思路

找出数组中是否有重复数字,简单的哈希表题,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
std::unordered_set<int> seen_nums;
for (int num: nums) {
if (seen_nums.count(num) != 0) return true;
seen_nums.insert(num);
}

return false;
}
};
  • 时间复杂度: O(n)
  • 空间复杂度: O(n)

当然还可以通过排序的方法,然后比较前后两个数字是否相同,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {

if (nums.empty()) return false;

std::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)
  • 空间复杂度: O(1)