1,题目要求
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
给定一个整数数组,查找数组是否包含任何重复项。
如果数组中任何值至少出现两次,则函数应返回true,如果每个元素都不相同,则返回false。
2,题目思路
对于这道题,要求判断一个数组中是否含有重复的数字。
我们可以直接用一个map来对数字出现的次数进行一个统计,或者使用一个更简单的策略——对数组进行排序,然后依次判断两两数字是否相等即可。
3,代码实现
static auto speedup = [](){
ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
int n = nums.size();
if(n <= 1)
return false;
sort(nums.begin(), nums.end());
for(int i = 0;i<n-1;i++){
if(nums[i] == nums[i+1])
return true;
}
return false;
}
};