[Leetcode][001] Two Sum (Java)

來源:互聯網
上載者:User

標籤:

題目在這裡: https://leetcode.com/problems/two-sum/

【標籤】Array; Hash Table

【個人分析】

     這個題目,我感覺也可以算是空間換時間的例子。如果是O(n^2)的那種思路,就是對於一個數字,去掃剩下的所有數字,看有沒有能夠加起來和為target的組合。但是如果加入一個雜湊表,我們掃過的數字都可以記錄下來。

  我用的是 (target - number) 作為key, 用number在nums中的 index 作為 value, 遇到一個新的數字number,如果它存在於map 中(說明我們先前遇到過target - number),那麼我們就是找到結果了。

 

 1 public class Solution { 2     public int[] twoSum(int[] nums, int target) { 3         int[] result = new int[2]; 4         Map<Integer, Integer> indexMap = new HashMap<Integer, Integer>(); 5         for (int i = 0; i < nums.length; i++) { 6             int number = nums[i]; 7             if (indexMap.containsKey(number)) { 8                 // found the two numbers we are looking for! 9                 // ! required result is not zero-based indexed, but 1-based10                 result[0] = 1 + indexMap.get(number);11                 result[1] = 1 + i;12                 break;13             } else {14                 // put the number we are expecting into the map15                 indexMap.put(target - number, i);16             }17         }18         return result;19     }20 21 }

 

[Leetcode][001] Two Sum (Java)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.