• 【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 [];
    }
    
  • 相关阅读:
    宏任务与微任务
    reactnative 自定义项目的图标库
    react-native中textInput在androidTV上的焦点处理(坑篇)
    js中!!的运用
    ES6里class杂乱随笔
    浅析链式调用
    link和@import的区别
    ES2020链判断运算符?.和Null判断运算符??
    vue组件使用name属性来生成递归组件
    k8s学习——相关概念
  • 原文地址:https://www.cnblogs.com/SiriusZHT/p/14310754.html
Copyright © 2020-2023  润新知