zoukankan      html  css  js  c++  java
  • 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];
       }
    };
    
    学无止境,谦卑而行.
  • 相关阅读:
    SSH服务附带----SFTP
    SSH附带的远程拷贝----SCP
    linux下的SSH服务
    model.form使用,配合form的钩子
    import_module 导入变量的包
    dir函数
    python爬虫之scrapy
    python爬虫之解析库Beautiful Soup
    django 过滤器,标签
    django 验证码实现
  • 原文地址:https://www.cnblogs.com/wangyang0210/p/14540428.html
Copyright © 2011-2022 走看看