[LeetCode] No.1 Two Sum

鏈接:https://leetcode.com/problems/two-sum/submissions/
原題:

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.
Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].

**UPDATE (2016/2/13):
**The return format had been changed to zero-based indices. Please read the above updated description carefully.

Subscribe to see which companies asked this question

分析:
這道題,要求是給一個數組,給一個數字,返回兩個數組元素之和等于這個數字的位置,而且說了,假設一個數組只有一個解法。
首先想到暴力破解,但是暴力破解很顯然不夠LeetCode的B格
在這題里面用到了Map

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
            Map<Integer, List<Integer>> maps = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
           if(maps.get(nums[i])!=null) {
                maps.get(nums[i]).add(i);
            } else {
                List<Integer> list = new ArrayList<>();
                list.add(i);
                maps.put(nums[i], list);
            }
        }
        for (int key : maps.keySet()) {
            int tmp = target - key;
            if(tmp == key && maps.get(key).toArray().length>1) {
                result[0] = (int) maps.get(key).toArray()[0];
                result[1] = (int) maps.get(key).toArray()[1];
                break;
            }
            if (maps.get(tmp) != null) {
                result[0] = maps.get(key).get(0);
                result[1] = maps.get(tmp).get(0);
                break;
            }
        }
        return result;
    }
}

這是一開始的方法

public class Solution {
    public int[] twoSum(int[] nums, int target) {
         HashMap<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.get(nums[i]) != null) {
                int[] result = {map.get(nums[i]) , i};
                return result;
            }
            map.put(target - nums[i], i);
        }

        int[] result = {};
        return result;
    }
}

后來改進的方法。

第一種方法是我自己的實現,第二種方法是看九章的實現。 在ac的過程中,第一種要耗時12ms, 第二種耗時6ms,仔細閱讀一下,確實發現是我太愚鈍了~

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容