美文网首页
HashMap的boolean containsKey(Obje

HashMap的boolean containsKey(Obje

作者: lllaser | 来源:发表于2017-06-15 23:37 被阅读0次

    最近开始刷了点LeetCode,算法的第一个题是Two Sum,看起来很简单吧?

    Given an array of integers, return indices of the two numbers such that they add up to a specific target.
    You may assume that each input would have exactly one solution, and you may not use the same element twice.
    Example:
    Given nums = [2, 7, 11, 15], target = 9,
    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].

    于是我的解法也很简单暴力

    public class Solution {
        public int[] twoSum(int[] nums, int target) {
            int[] result = new int[2];
            for (int i = 0; i < nums.length; i++) {
                int a = nums[i];
                for (int j = i + 1; j < nums.length; j++) {
                    int b = nums[j];
                    if (a + b == target) {
                        result[0] = i;
                        result[1] = j;
                    }
                }
            }
            return result;
        }
    }
    

    这种方法嵌套两层循环,时间复杂度分别是O(n),于是总的时间复杂度是O(n^2)
    打开Editorial Solution发现了这种时间复杂度是O(n),空间复杂度增加到O(n)的解法。

    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], i);
        }
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (map.containsKey(complement) && map.get(complement) != i) {
                return new int[] { i, map.get(complement) };
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }
    

    咦?时间复杂度为什么是O(n)?是时候来看看HashMap源码了。
    先用查找找到containsKey(Object 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 getNode(hash(key), key) != null;
        }
    

    containsKey方法调用了getNode(hash(key), key)方法,若结果非null则返回true,否则返回false。所以getNode(hash(key), key)方法就是问题的关键。

        /**
         * Implements Map.get and related methods
         *
         * @param hash hash for key
         * @param key the key
         * @return the node, or null if none
         */
        final Node<K,V> getNode(int hash, Object key) {
            Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
            if ((tab = table) != null && (n = tab.length) > 0 &&
                (first = tab[(n - 1) & hash]) != null) {
                if (first.hash == hash && // always check first node
                    ((k = first.key) == key || (key != null && key.equals(k))))
                    return first;
                if ((e = first.next) != null) {
                    if (first instanceof TreeNode)
                        return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                    do {
                        if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k))))
                            return e;
                    } while ((e = e.next) != null);
                }
            }
            return null;
        }
    

    这个代码初看有点复杂,理解原理的关键点在于

    • 返回值Node<K, V>是什么
    • 代码第三行tab = table中的table是什么
        /**
         * Basic hash bin node, used for most entries.  (See below for
         * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
         */
        static class Node<K,V> implements Map.Entry<K,V> {
            final int hash;
            final K key;
            V value;
            Node<K,V> next;
    
            Node(int hash, K key, V value, Node<K,V> next) {
                this.hash = hash;
                this.key = key;
                this.value = value;
                this.next = next;
            }
    
            public final K getKey()        { return key; }
            public final V getValue()      { return value; }
            public final String toString() { return key + "=" + value; }
    
            public final int hashCode() {
                return Objects.hashCode(key) ^ Objects.hashCode(value);
            }
    
            public final V setValue(V newValue) {
                V oldValue = value;
                value = newValue;
                return oldValue;
            }
    
            public final boolean equals(Object o) {
                if (o == this)
                    return true;
                if (o instanceof Map.Entry) {
                    Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                    if (Objects.equals(key, e.getKey()) &&
                        Objects.equals(value, e.getValue()))
                        return true;
                }
                return false;
            }
        }
    

    可见,Node<K, V>是一个存放有Key和Value的链表节点。

        /**
         * The table, initialized on first use, and resized as
         * necessary. When allocated, length is always a power of two.
         * (We also tolerate length zero in some operations to allow
         * bootstrapping mechanics that are currently not needed.)
         */
        transient Node<K,V>[] table;
    

    tableNode<K, V>数组,这里的Node<K, V>则是某一hash值链表的头节点(不同key的hash值可能重复,将会被存放在后续的节点中)。值得注意的是,数组table的长度是2的倍数

    现在回到getNode(hash(key), key)方法中。先看代码第五行

    first = tab[(n - 1) & hash]
    

    没错,我们发现了一个大幂幂,key对应的头节点在数组table中的存放位置,也就是下标是(n - 1) & hash这个位运算的结果。n是table的长度(必为2的倍数),则n - 1就是table下标的取值范围,用二进制表示是1111...,共log(n)个1。因此(n - 1) & hash实际上是取了hash二进制形式的后n位数,正好能对应数组table的下标。
    数组通过下标访问Node<K, V>的时间复杂度是O(1),而Node<K, V>访问字段的时间复杂度也是O(1),如果头节点后没有节点,时间复杂度就是O(1)。
    头节点后存在节点时,则按下面的代码遍历这些节点,时间复杂度大于O(1)。

                if ((e = first.next) != null) {
                    if (first instanceof TreeNode)
                        return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                    do {
                        if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k))))
                            return e;
                    } while ((e = e.next) != null);
                }
    

    至于如何尽量避免产生相同的位运算值,那就是hash算法的事了,不在本文讨论范围内。实际上一个好的hash算法是可以让平均时间复杂度为O(1)的。

    至此,containsKey(Object key)方法的时间复杂度问题就基本解决了。

    写完这篇文章我就发现啊,原来LeetCode最简单的Two Sum也能学到这么多东西,还是好好去刷LeetCode吧。

    参考资料

    https://leetcode.com/articles/two-sum/

    相关文章

      网友评论

          本文标题:HashMap的boolean containsKey(Obje

          本文链接:https://www.haomeiwen.com/subject/jpiuqxtx.html