LeetCode Two Sum(001)解法總結

NewCoder1024發表於2020-03-05

描述

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].複製程式碼

思路

先使用for迴圈確定當前數字,再巢狀一個for迴圈匹配第二個數字,一旦滿足要求,就進行返回。

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] out = new int[2];
        for(int i =0;i<nums.length;i++){
            boolean flag = false;
            for(int j =i+1;j<nums.length;j++){
                if(nums[i] + nums[j] == target){
                    out[0] = i;
                    out[1] = j;
                    flag = true;
                    break;
                }
            }   
            if(flag){
                break;
            }
        }
        return out;
    }
}複製程式碼

可以暴力AC,但是時間複雜度和空間複雜度都不是很好。

Runtime: 59 ms, faster than 18.99% of Java online submissions for Two Sum.
Memory Usage: 39.3 MB, less than 6.43% of Java online submissions for Two Sum.

優化

看到問題討論區有使用map作為輔助查詢工具的,可以大大提高資料檢索速度。

public int[] twoSum(int[] numbers, int target) {
    int[] result = new int[2];
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    for (int i = 0; i < numbers.length; i++) {
        if (map.containsKey(target - numbers[i])) {
            result[1] = i;
            result[0] = map.get(target - numbers[i]);
            return result;
        }
        map.put(numbers[i], i);
    }
    return result;
}複製程式碼

該演算法的思路是:使用for迴圈進行遍歷,當前資料為i所記錄的位置,但是不同的是它進行前向查詢,將當前資料和之前已經完成遍歷的資料匹配。這樣做的好處在於可以將已遍歷過的資料加入map集合,方便進行比對、節約檢索時間和回退時間,且不會出現二次匹配成功的問題。

Runtime: 1 ms, faster than 99.90% of Java online submissions for Two Sum.
Memory Usage: 42.4 MB, less than 5.65% of Java online submissions for Two Sum.

可以看到時間複雜度大幅提高,空間開支增加。


相關文章