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.
Subscribe to see which companies asked this question
//C++简单排序
class Solution {
public:
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;
}
};
//C++ 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;
}
};
//JAVA
public class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer>unique =new HashSet<Integer>();
for(int t:nums){
if(unique.contain(t))
return true;
else
unique.add(t);
}
return false;
}
}