Leetcode 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.
解题思路:
判断array里是否有重复,就想到一种不能有重复的数据结构set, 如果已经有了这个值,则return true, 否则就加进这个set.
当然,set 也有不同的用法。写了两种。
Java code:
public boolean containsDuplicate(int[] nums) { Set<Integer> values = new HashSet<Integer>(); for(int i=0; i< nums.length; i++) { if(values.contains(nums[i])){ return true; } values.add(nums[i]); } return false; }
或者:
public boolean containsDuplicate(int[] nums) { Set<Integer> values = new HashSet<Integer>(); for(int i=0; i< nums.length; i++) { if(!values.add(nums[i])){ return true; } } return false; }