Title: Contains Duplicate Source: leetcode.com
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.
Java solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
/* https://leetcode.com/problems/contains-duplicate/ */ import java.util.HashSet; public class ContainsDuplicate { public static void main(String args[]) { } public boolean containsDuplicate(int[] nums) { HashSet<Integer> set = new HashSet<Integer>(); for(int i=0;i<nums.length;i++) { if(!set.contains(nums[i])) { set.add(nums[i]); } else { return true; } } return false; } } |