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.
题目含义:
给定整数数组,查找数组是否包含任何重复项。如果数组中的任何值至少出现两次,则函数应返回true,如果每个元素都不同,则返回false。
思想:先用库函数快排排序
判断相邻的两个值是否相同
C++ AC代码:时间o(nlogn) 空间o(1)
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
int len = nums.size();
sort(nums.begin(),nums.end());
bool flag = false;
for(int i=0;i<len-1;i++){
if(nums[i]==nums[i+1]){
flag = true;
break;
}
}
return flag;
}
};

本文介绍了一种使用快速排序算法来检查整数数组中是否存在重复元素的方法。通过排序数组后比较相邻元素的方式,实现了一个时间复杂度为O(nlogn)且空间复杂度为O(1)的解决方案。
669

被折叠的 条评论
为什么被折叠?



