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与每个元素的差值,然后利用数组的indexOf()方法在剩余的数组值中查找差值,如果有,则将当前索引与indexOf()方法查找的索引保存在数组中,返回。


    /**
     * @param {number[]} nums
     * @param {number} target
     * @return {number[]}
     */
    var twoSum = function(nums, target) {
        var result = [];
        for(var i=0; i<nums.length; i++) {
            var tmp = target - nums[i];
            var index = nums.indexOf(tmp, i+1);
            if(index !== -1) {
                result.push(i, index);
                break;
            }
        }
        if(result.length === 0) {
            console.log('not found')
        }
        return result;
    };
  • 结论:耗时335ms,只有17%的beats。。。初版,总算完成了。


Kyxy
316 声望10 粉丝