您的位置:首页 > 大数据 > 人工智能

[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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode hashSet