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; }