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