• 【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 [];
    }
    
  • 相关阅读:
    Python
    deleted
    deleted
    ZOJ 3593 One Person Game(ExGcd + 最优解)题解
    ZOJ 3609 Modular Inverse(扩展欧几里得)题解
    P2234 [HNOI2002]营业额统计(Splay树)题解
    FJUT seventh的tired树上路径(01字典树)题解
    HDU 4825 Xor Sum(01字典树)题解
    Newcoder Metropolis(多源最短路 + Dijkstra堆优化)题解
    HDU 5938 Four Operations(乱搞)题解
  • 原文地址:https://www.cnblogs.com/SiriusZHT/p/14310754.html
Copyright © 2020-2023  润新知