zoukankan      html  css  js  c++  java
  • 【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 [];
    }
    
  • 相关阅读:
    aaa
    记一次Vue实战总结
    Data too long for column 'xxx' at row 1MySql.Data.MySqlClient.MySqlPacket ReadPacket() 报错解决
    uni-app 监听返回按钮
    微信H5分享外部链接,缩略图不显示
    uni-app 动态控制下拉刷新
    vueX 的使用
    uni-app H5 腾讯地图无法导航
    uni-app支付功能
    hooks 与 animejs
  • 原文地址:https://www.cnblogs.com/SiriusZHT/p/14310754.html
Copyright © 2011-2022 走看看