Two Sum

一 問題描述

Two Sum

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

翻譯:
給定一個整數數組,返回其中兩個加起來和給定的target數值相等的元素的下標。每一個測試用例保證只有一個結果,並且,數組中沒有重複的元素。

二 解法

1. 第一解法(自己)

思路:
輸入一個數組和一個整數,從前往後遍歷這個數組,用每一個元素和之後的每一個元素相加與target比較。
代碼:

    var twoSum = function(nums, target) {
        
        for (let i = 0; i < nums.length; i++) {
            for(let j = i+1; j < nums.length; j++) {
                if (nums[i] + nums[j] === target)
                    return [i, j];
            }
        }
        
    };

結果:

29 / 29 test cases passed.
Status: Accepted
Runtime: 128 ms
Memory Usage: 34.8 MB

2. 改進解法(社區)

思路:
利用Javascript提供的Map數據結構,將輸入的數組元素值作爲map的key,下標作爲value。只遍歷一次數組,將每一個元素與target相減,得到的數字在map中查找是否存在。如果存在,說明兩數相加得到target,返回map的值。如果不存在,將這個元素和下標存入map。
這樣做的好處就是,只遍歷一遍數組。查找map的哈希算法比for要快得多。並且,由於一開始map是空的,所以,效率比從一開始就兩次遍歷也高得多。
代碼:

    var twoSum = function(nums, target) {
        
        let seen = new Map();
        let value = 0;
        
        for (let i = 0;i < nums.length; i++) {
            value = target - nums[i];
            
            if (seen.has(value)) {
    		     // 注意,這裏兩個順序是固定的,因爲題目中的要求是小的下標在前, 
    			// seen中放的是之前查抄過的,必定下標小於i
                return [seen.get(value), i];
            }
            seen.set(nums[i], i);
        }
        return [];
        
    };

結果:

29 / 29 test cases passed.
Status: Accepted
Runtime: 64 ms
Memory Usage: 35.1 MB

By DoubleJan
2019.7.5

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章