卖萌的弱渣

I am stupid, I am hungry.

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.

  • Java: hash_set
(Contains-Duplicate.java) download
1
2
3
4
5
6
7
8
9
10
public class Solution {
    public boolean containsDuplicate(int[] nums) {
        final Set<Integer> distinct = new HashSet<Integer>();
        for (int num : nums){
            if(!distinct.add(num))
                return true;
        }
        return false;
    }
}
(Contains-Duplicate.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution(object):
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        if len(nums) == 0:
            return False
        hash_map = dict()
        for i in range(len(nums)):
            if nums[i] not in hash_map:
                hash_map[nums[i]] = i
            else:
                return True
        return False