题目:
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.
链接: http://leetcode.com/problems/contains-duplicate/
题解:
求数组中是否有重复元素。第一反应是用HashSet。 还可以用Bitmap来写。二刷要都补充上。
Time Complexity - O(n), Space Complexity - O(n)
public class Solution { public boolean containsDuplicate(int[] nums) { if(nums == null || nums.length == 0) return false; Set<Integer> set = new HashSet<>(); for(int i : nums) { if(set.contains(i)) return true; else set.add(i); } return false; } }
Reference:
https://leetcode.com/discuss/70186/88%25-and-99%25-java-solutions-with-custom-hashing
https://leetcode.com/discuss/59208/20ms-c-use-bitmap
https://leetcode.com/discuss/37219/possible-solutions
https://leetcode.com/discuss/37190/java-o-n-ac-solutions-with-hashset-and-bitset
原文:http://www.cnblogs.com/yrbbest/p/4987090.html