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 [];
    }
    
  • 相关阅读:
    python dict
    用Python requests beautifulSoup 获取并显示中文信息
    Python information to learn
    Python 中的异常
    Python 中的函数
    安装Linux系统Fedora 23
    (转)开源协议的比较
    WizNote for linux installation
    linux下编译bib、tex生成pdf文件
    NLP学术组织、会与论文
  • 原文地址:https://www.cnblogs.com/SiriusZHT/p/14310754.html
Copyright © 2011-2022 走看看