[217] Contains Duplicate
2016-06-26 15:35
357 查看
1. 题目描述
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,2,3,4,2],包含重复数字2。
2. 解题思路
使用一个hashSet边读入边判断元素是否有重复,有重复就退出。3. Code
public class Solution { public boolean containsDuplicate(int[] nums) { Set<Integer> set = new HashSet<>(); for (int i = 0; i < nums.length; ++i) { // hashset是否包含当前元素 if(set.contains(nums[i])) { // 若包含,元素存在重复 return true; } set.add(nums[i]); } return false; } }
// hashSet内部使用一个hashMap,把每一个值都当做hashMap中的key /** * Returns <tt>true</tt> if this map contains a mapping for the * specified key. * * @param key The key whose presence in this map is to be tested * @return <tt>true</tt> if this map contains a mapping for the specified * key. */ public boolean containsKey(Object key) { return getEntry(key) != null; } /** * Returns the entry associated with the specified key in the * HashMap. Returns null if the HashMap contains no mapping * for the key. */ final Entry<K,V> getEntry(Object key) { if (size == 0) { return null; } int hash = (key == null) ? 0 : hash(key); for (Entry<K,V> e = table[indexFor(hash, table.length)]; e != null; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } return null; }
相关文章推荐
- Java中HashMap和Hashtable及HashSet的区别
- 浅析Java中Map与HashMap,Hashtable,HashSet的区别
- HashSet详解
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- 利用HashSet生成一组不重复的随机数
- leetcode----Longest Substring Without Repeating Characters
- Java集合HashSet中的两个对象怎样算重复
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02