217. Contains Duplicate

  • 44.4%

https://leetcode.com/problems/contains-duplicate/

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.


方法一:

58ms, 31.23%, July 13th, 2016

1
2
3
4
5
6
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
return nums.size() > set<int>(nums.begin(), nums.end()).size();
}
};

方法二:

https://discuss.leetcode.com/topic/16706/basic-48ms-c-solution-with-unordered_map

Basic 48ms C++ solution with unordered_map

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
if (nums.empty()) { return false; }
unordered_map<int,int> mp;
for (int i : nums) {
if (++mp[i] > 1) {
return true;
}
}
return false;
}
};

方法三:

使用unordered_set

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
if(nums.empty())
return false;
unordered_set<int> set;
for(auto num:nums){
if(set.find(num)!=set.end())
return true;
set.insert(num);
}
return false;
}
};

python


1
2
3
4
5
6
7
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
return len(nums) != len(set(nums))


java


solution 1:

6ms, 79.29%, July 13th, 2016

1
2
3
4
5
6
7
8
9
public class Solution {
public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums);
for(int ind = 1; ind < nums.length; ind++)
if(nums[ind] == nums[ind-1])
return true;
return false;
}
}

solution 2:

15ms, 30.86%, July 13th, 2016

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Solution {
public boolean containsDuplicate(int[] nums) {

Set<Integer> distinct = new HashSet<Integer>();
for(int num : nums) {
if(distinct.contains(num)) {
return true;
}
distinct.add(num);
}
return false;
}
}

solution 3:

10ms, 54.48%, July 13th, 2016

1
2
3
4
5
6
7
8
9
public class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
for(int i : nums)
if(!set.add(i))
return true;
return false;
}
}
谢谢你,可爱的朋友。