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;
//解决方法:利用map,遍历数组,每访问一个元素,看其是否在map中出现,如已出现过,则存在重复元素,如没有,则将元素加入到map中。
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
map<int, int> int_map;
for (int i = 0; i < nums.size(); ++i){
if (int_map.count(nums[i]))
return true;
int_map.insert(pair<int, int>(nums[i], i));
}
return false;
}
};

本文介绍了一种使用哈希表来判断整数数组中是否存在重复元素的方法。通过遍历数组并检查每个元素在哈希表中是否已存在,可以有效检测数组中是否有重复项。
2491

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



