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.輸入一個整數的數組,若是數組中的元素有重複的,那麼返回true,若是數組中的元素都是惟一的,那麼返回false算法
public boolean containsDuplicate(int[] nums) { int length = nums.length; if(length <= 1){ return false; } HashMap<Integer,Integer> count = new HashMap<Integer, Integer>(); count.put(nums[0], 1); for(int i = 1;i<nums.length;i++){ int tempKey = nums[i]; if(count.get(tempKey) != null ){ return true; }else{ count.put(tempKey, 1); } } return false; }
public boolean containsDuplicate(int[] nums) { int length = nums.length; if(length <= 1){ return false; } Arrays.sort(nums); for(int i=0 ;i<length-1;i++){ if(nums[i] == nums[i+1]){ return true; } } return false; }