问题分描述:
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.
问题分析:
判断数组中是否含有重复元素,可利用map键值对来进行判断,也可以将数组转换为集合set,比较set和vector的size是否一样。
过程详见代码:
map:
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
map<int,int> m;
for(int i = 0; i < nums.size(); i++)
{
if(m.count(nums[i]) == 0)
{
m.insert(pair<int,int>(nums[i],1));
}
else if(m.count(nums[i]) >= 1) return true;
}
return false;
}
};
set:
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
return set<int>(nums.begin(), nums.end()).size() < nums.size();
}
};