ArrayList's contains method and Hasmap's containskey efficiency are 10 times times worse.

Source: Internet
Author: User

The problem stems from a question on Leetcode:

Twosum:

Given an array of integers, return indices of the both numbers such that they add-to a specific target.

You may assume this each input would has exactly one solution.

Example:

Given nums = [2, 7, one, +], target = 9,because nums[0] + nums[1] = 2 + 7 = 9,return [01].
The general solution to this problem is a relatively easy to think of the solution is: two traversal, but the complexity will reach O (N2). A better solution is to use hashmap complexity to reduce to O (n). At first I used the idea of a similar hashmap, using ArrayList to do, the code is as follows:

Public int[] Twosum (int[] nums, int target) {        arraylist<integer> list = new arraylist<integer> ();                for (int i=0; i<nums.length; i++) {        if (List.contains (Target-nums[i])) {        return new Int[]{list.indexof ( Target-nums[i]), i};        }        List.add (Nums[i]);        }        return null;    }

The results found that the efficiency and the stupid method are similar, the running time has not been improved, the test case on the website run time is 56ms, only beat hundred percent more than 10. Later used HashMap to do:

Public int[] Twosum (int[] nums, int target) {        Hashmap<integer, integer> map = new Hashmap<integer, Integer> ;();                for (int i=0; i<nums.length; i++) {        if (Map.containskey (Target-nums[i])) {        return new Int[]{map.get ( Target-nums[i]), i};        }        Map.put (Nums[i], i);        }        return null;    }
Efficiency has been significantly improved: 6ms, the only difference between the two code is one with ArrayList storage elements, the other with HashMap. Nearly 10 times times the efficiency difference!

Why there is such a big gap:

Cause when ArrayList uses arrays to store elements, HashMap uses a hash table to store the elements. In the above two pieces of code, the efficiency gap is in the contains and ContainsKey methods.

The contains method of ArrayList is judged by calling its own index of method:

public int indexOf (Object o) {        if (o = = null) {for            (int i = 0; i < size; i++)                if (elementdata[i]==null) 
   return i;        } else {for            (int i = 0; i < size; i++)                if (O.equals (Elementdata[i]))                    return i;        }        return-1;    }
As you can see, in the source code, the index method iterates through the entire array sequence, which is undoubtedly the least efficient way to find it.

In the Hashmap,key is stored in the hash table, the search is on the hash table to find, about the hash table lookup method is very simple here do not repeat.

public boolean ContainsKey (Object key) {        return GetNode (hash (key), key)! = NULL;    }
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])! = Nu LL) {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&                gt;) 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; }


In short, if you want to use the Contains method, with HashMap to replace is far faster than ArrayList, if you want to traverse the words or use ArrayList it.



ArrayList's contains method and Hasmap's containskey efficiency are 10 times times worse.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.