/**
* 两数之和: 使用两遍循环, 问是不是可以组成target的两个数.
* @param {number[]} nums
* @returns {number[]}
*/
function twoSum(nums, target) {
let ress = []
for(let i= 0; i< nums.length; i++){
for(let j =0; j<i; j++){
if(nums[i] + nums[j] === target){
let res= i> j? [j, i]: [i, j]
ress.push(res)
}
}
}
return ress
}
const nums = [1, 2, 3, 4, 5, 6, 0]
const target = 5
const result = twoSum(nums, target)
console.log(result);
/**
* 一层循环+Map
* @param {number[]} nums
* @param {number} target
*/
function twoSumMap(nums, target) {
let mar = new Map()
let res= [ ]
// 这样一遍的循环就可以了, 这样可以减少时间复杂度.
for(let i=0; i< nums.length; i++) {
const rest = target - nums[i]
if(mar.has(rest)){
// 只是为了输出的数字按序
i> mar.get(rest) ? res.push([mar.get(rest),i]):res.push( [i, mar.get(rest)])
}else {
mar.set(nums[i], i)
}
}
return res
}
const res = twoSumMap(nums, 5)
console.log(res);
leetcode 1-2つの数値の合計。
おすすめ
転載: blog.csdn.net/weixin_40944062/article/details/113104555
おすすめ
ランキング