LeetCode 01 || twoSum

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.数组

有一个整数数组,返回其中两个值之和为指定值的索引。假设每一个输入指定值只有一个解,而后不能使用同一个元素两次code

Example:索引

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

初版

思路:先想到的确定是两次循环。遍历数组每一个元素,获target与每一个元素的差值,而后利用数组的indexOf()方法在剩余的数组值中查找差值,若是有,则将当前索引与indexOf()方法查找的索引保存在数组中,返回。ci

/**
     * @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。。。第一版,总算完成了。element

相关文章
相关标签/搜索