LeetCode,leetcodeoj

來源:互聯網
上載者:User

LeetCode,leetcodeoj

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].

 

解法1:暴力搜尋

 

1 public int[] twoSum(int[] nums, int target) {2     for (int i = 0; i < nums.length; i++) {3         for (int j = i + 1; j < nums.length; j++) {4             if (nums[j] == target - nums[i]) {5                 return new int[] { i, j };6             }7         }8     }9 }

 

解法2:Hash Table

 1 public int[] twoSum(int[] nums, int target) { 2     Map<Integer, Integer> map = new HashMap<>(); 3     for (int i = 0; i < nums.length; i++) { 4         int complement = target - nums[i]; 5         if (map.containsKey(complement)) { 6             return new int[] { map.get(complement), i }; 7         } 8         map.put(nums[i], i); 9     }10 }

雜湊表(Hash table,也叫散列表),是根據key而直接進行訪問的資料結構。也就是說,它通過把key映射到表中一個位置來訪問記錄,以加快尋找的速度。這個映射函數叫做散列函數,存放記錄的數組叫做散列表。雜湊表的做法其實很簡單,就是把key通過一個固定的演算法函數即所謂的雜湊函數轉換成一個整型數字,然後就將該數字對數組長度進行取餘,取餘結果就當作數組的下標,將value儲存在以該數字為下標的數組空間裡。而當使用雜湊表進行查詢的時候,就是再次使用雜湊函數將key轉換為對應的數組下標,並定位到該空間擷取value,如此一來,就可以充分利用到數組的定位效能進行資料定位。

 解法2中的核心方法

map.containsKey(complement)

其源碼如下:

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]) != 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;    }

嗯,看不太明白!!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.