1. 程式人生 > >Leetcode 之 TwoSum

Leetcode 之 TwoSum

從今天開始在LeetCode上刷題了,第一題,雖然很簡單,但是因為剛剛學習了java,而且程式碼一直寫的都很爛,所以過程還是有點曲折的,值得記錄下~

LeedCode原題:
Two Sum

看到題目以後,想法是使用陣列進行雙重迴圈好了,所以編寫程式碼如下:

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

除錯執行竟然順利Finished!不禁想要歡呼~

但是還是覺得這麼寫有點low,於是在網上查詢了其他的方法,驚奇的發現,有的人使用雙重迴圈,因為時間複雜度沒有通過,不知道為什麼我的成功了~

而參看有人提出的使用hashmap,將數值作為key,索引值作為value,程式碼如下:

public class Solution {
    public int[] twoSum(int[] nums, int target) {
         int len = nums.length;
        Map<Integer,Integer> map = new HashMap();
        for(int i=0;i<len;i++)
        {
            map.put(nums[i],i);//nums的值傳入HashMap
if (map.containsKey(target - nums[i])) { int n = map.get(target - nums[i]); if(n<i)//題目規定同一個資料不能使用兩次 return new int[]{map.get(target - nums[i]), i}; } } return new int[]{-1, -1}; } }

好長時間沒有刷leetcode了,最近又重新撿起來,因為要找工作啊啊啊啊啊,但是最基本的都還是會搞錯,不過不要灰心,多練習一定可以的。
上面的第二種解法是4月份的時候刷題記錄下來的,都不記得當時是否有真的執行過,這次重新看過這道最簡單的題目,搞了半天才發現是錯誤的,因為hashmap中的key值是不能重複的,如果有重複的key,則value會被覆蓋,所以例如nums = {3,3},那麼hashmap的size最終只能是1個,但是該題目中數不能重複利用,所以是error!

改進,基本思路還是不變,但是首先先要判斷target-nums[i]是否在hashmap中有key值,如果沒有再存入到hashmap中,這樣相當於是在nums[0]到nums[i-1]的hashmap中找符合條件的target-nums[i]。
程式碼如下:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        int len = nums.length;
        int[] re = new int[2];
        for(int i=0;i<len;i++){
            int tmp = target - nums[i];
            if(map.containsKey(tmp))
            {
                re[0] = map.get(tmp);
                re[1] = i;
            }
            map.put(nums[i],i);// 最關鍵的是這條語句的位置
        }

        return re;

    }
}