Contains Duplicate(leetcode217)

Given an array of integers, find if the array contains any duplicates.git

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.github

Example 1:数组

Input: [1,2,3,1]
Output: true

Example 2:app

Input: [1,2,3,4]
Output: false

Example 3:code

Input: [1,1,1,3,3,4,3,2,4,2]
Output: true

实现:element

public boolean containsDuplicate(int[] nums) {
    Set<Integer> set = new HashSet<Integer>();
    for(int i : nums) {
        //这里用了set,其实set是去重的,虽然判断size也行,可是效率比不上中间过程就能够判断
        //add方法里面用的也是 map的put 其实用map就好了
        if(!set.add(i))
        {
            return true;
        }
    }
    return false;
}

 

public boolean containsDuplicate2(int[] nums) {
    Map<Integer,Integer> map = new HashMap();
    for(int i : nums) {
        if(map.put(i,i) != null)
        {
            return true;
        }
    }
    return false;
}

//固然还有一种作法是 我能够开辟和数组同样大的数组 或者使用map放入中,根据value的值来判断
//固然实践复杂度不考虑的话 那么能够每一个都便利一遍判断

 

git:https://github.com/woshiyexinjie/leetcode-xinleetcode

相关文章
相关标签/搜索