Description:
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.
My Solution:
class Solution { public boolean containsDuplicate(int[] nums) { Map<Integer,Integer> map = new HashMap<Integer,Integer>(); int len = nums.length; for(int i = 0;i < len;i++){ map.put(nums[i],(map.get(nums[i]) == null)?1:map.get(nums[i])+1); } for(Integer key : map.keySet()){ if(map.get(key) > 1){ return true; } } return false; } }
Better Solution 1:
//数组排序后判断相邻元素是否相等 public boolean containsDuplicate(int[] nums) { Arrays.sort(nums); for (int i = 0; i < nums.length - 1; ++i) { if (nums[i] == nums[i + 1]) return true; } return false; }
Better Solution2:
//用到set的contains和add public boolean containsDuplicate(int[] nums) { Set<Integer> set = new HashSet<>(nums.length); for (int x: nums) { if (set.contains(x)) return true; set.add(x); } return false; }
Best Solution:
//先求出nums数组的最小值min和最大值max,然后新建boolean数组,下标为最小值到最大值之间的所有元素,遍历nums,如果一个元素j出现,将boolean数组(j - min)下标对应的值设置为true,如果下次遍历到j,那么返回true class Solution { public boolean containsDuplicate(int[] nums) { if (nums.length <= 1) return false; int minNum = nums[0]; int maxNum = nums[0]; for (int num : nums) { if (minNum > num) { minNum = num; } if (maxNum < num) { maxNum = num; } } if (maxNum == minNum) return true; boolean[] visit = new boolean[maxNum - minNum + 1]; for (int num : nums) { int idx = num - minNum; if (visit[idx]) { return true; } else { visit[idx] = true; } } return false; } }
总结:一个还是要看元素排列的规律(排序后判断相邻元素是否相等的方法),还有就是数组元素出现次数这种问题一般都能设置一个以对应元素为下标的数组用来计算出现次数。
版权声明:本文为博主原创文章,未经博主允许不得转载。