使用HashMap巧求重复元素
题目:数字1-1000放在一个长度为1001的int 类型的数组中,其中只有一个数字是重复的,求这个重复数字是哪个?(要求所有元素最多只能取一次)
偶然看到这样一个题,想到最近看的HashMap源码,可以巧用HashMap来解答此题,先贴下答案。(这里用一个11位的数组演示)
1、解题代码
import java.util.HashMap;
public class getDuplicate {
public static int getDup(int E[]){
Integer key = 0;
HashMap<Integer, Integer> hashmap = new HashMap<>();
for (int i = 0; i < E.length; i++) {
key = hashmap.put(E[i],E[i]);
if (null != key){
break;
}
}
return key;
}
public static void main(String[] args) {
int E[] = {1,2,3,4,5,6,7,8,9,3};
System.out.println("The duplicate element is " +getDup(E));
}
}
结果
The duplicate element is 3
2、解题思路
如果题目只是找重复元素,很简单,只需要将元素重复比较即可。但是所有元素只允许取一次。就不能用常规的比较来求值。
这里想到Object.HashCode方法对于每个不同的元素得到的hash值是唯一的。我们把数组里的所有元素放入hashmap中,这里让元素既作为key,也作为value。如果元素不相同,则hashmap会不断新增;如果有相同元素,即key值相同,则hashmap会覆盖。
HashMap中put方法,如果是新增元素,则会返回null;
如果是覆盖元素,则会返回oldValue;
参考源码如下:
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue; // *覆盖原来值,则会返回oldValue*
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null; //*正常新增,会返回null*
}
3、补充说明
而且这里遍历元素的个数是跟重复元素的位置有关,而不是遍历所有的元素,如下:
import java.util.HashMap;
public class getDuplicate {
public static int getDup(int E[]){
Integer key = 0;
int count = 0;
HashMap<Integer, Integer> hashmap = new HashMap<>();
for (int i = 0; i < E.length; i++) {
key = hashmap.put(E[i],E[i]);
count++;
if (null != key){
break;
}
}
System.out.println(count);
return key;
}
public static void main(String[] args) {
int E[] = {1,2,3,4,5,6,3,7,8,9};
System.out.println("The duplicate element is " +getDup(E));
}
}
结果
7
The duplicate element is 3
欢迎评论补充新方法。