1. 程式人生 > >Contains Duplicate(leetcode217)

Contains Duplicate(leetcode217)

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.

Example 1:

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

Example 2:

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

Example 3:

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

實現:

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-xin