【Leetcode刷题篇】1.两数之和(JS)

题目来源:力扣(LeetCode)
题目链接:https://leetcode-cn.com/problems/

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.

示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

暴力枚举

JS

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
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];
            }else{
                continue;
            }
        }
    }
};

使用map

JS

  • 思路
  1. 创建一个map
  2. for循环遍历nums数组
  3. 用target减去nums的每一项nums[i],
    为了计算哪一项要跟当前数字相加得到target
  4. 检查map有没有这个数,有则返回结果,
    没有就把num[i]当作key
    i当作value放入map中
var twoSum = function(nums,target){
	const map = new Map();
	for(let i = 0; i < nums.length; i++){
		const complement = target - nums[i];
		if(map.has(complement)){
			return [map.get(complement),i];
		}else{
			map.set(nums[i],i);
		}
	}
	return [];
}
posted @ 2020-12-11 18:58  嗨Sirius  阅读(64)  评论(0编辑  收藏  举报