LeetCode OJ 217.Contains Duplicate
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.
这个问题比较简单,判断一个数组里的是否有重复出现的数字。代码简单如下:
1 public class Solution { 2 public boolean containsDuplicate(int[] nums) { 3 Map<Integer,Integer> map = new HashMap<>(0); 4 5 for(int num : nums){ 6 if(map.containsKey(num)) return true; 7 map.put(num,0); 8 } 9 return false; 10 } 11 }
1 public class Solution { 2 public boolean containsDuplicate(int[] nums) { 3 if(nums == null || nums.length <= 1) return false; 4 5 Set<Integer> set = new HashSet<>(); 6 for(int num : nums) { 7 if(!set.add(num)) return true; 8 } 9 return false; 10 } 11 }