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.
实现
bool containsDuplicate(vector<int>& nums) {
std::sort(nums.begin(), nums.end());
for (int i = 1; i < nums.size(); i++) {
if (nums[i-1] == nums[i]) return true;
}
return false;
}
本文介绍了一种使用排序方法来检查数组中是否存在重复元素的有效算法。通过先对整数数组进行排序,然后遍历数组比较相邻元素,如果找到相等的元素则表明数组中有重复项。

589

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



