leetcode——两数之和【一】

前言

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.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers

题目

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1]

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

Constraints:

2 <= nums.length <= 103
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.

解题

PHP

class Solution {

    /**
     * @param Integer[] $nums
     * @param Integer $target
     * @return Integer[]
     */
    function twoSum($nums, $target) {
        //定义数组存放下标值
        $indices = [];
        foreach ($nums as $key => $val) {
            //得到差异值
            $diff = $target - $val;
            //判断差异值是否在数组$indices中
            //如果不在数组$indices,就将key存入$indices数组中,继续寻找
            //若在数组则直接返回
            if (!isset($indices[$diff])) {
                $indices[$val] = $key;
                continue;
            }
            return [$indices[$diff], $key];
        }
    }
}

JavaScript


/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
   //创建一个map对象
   const map = new Map();
    //同PHP思路一致
   for(var i= 0; i<nums.length; i++) {
       let diff = target - nums[i];
       if (!map.has(diff)) {
           map.set(nums[i],i)
           continue;
       }
       return [map.get(diff), i];
   }
};
posted @ 2021-03-15 22:25  。思索  阅读(62)  评论(0编辑  收藏  举报