说明:现阶段的解题暂未考虑复杂度问题
Question:
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.
中文题目:
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
个人分析:
Answer:
var twoSum = function(nums, target) {
var res = {}
for (var i = 0; i < nums.length; i++) {
var other = target - nums[i]
if (res[other] !== undefined) {
return [res[other] , i]
} else {
res[nums[i]] = i
}
}
return []
};
其他:
这道题之前在其他地方见过,当时使用的暴力破解法:两个 for 循环嵌套
var twoSum = function(nums, target) {
for (var i = 0; i < nums.length; i++) {
for (var j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] === target) {
return [i, j]
}
}
}
}
本题更多 JavaScript 解析,请看「了解更多」
本文暂时没有评论,来添加一个吧(●'◡'●)