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];
       }
    };
    
    学无止境,谦卑而行.
  • 相关阅读:
    java的Scanner获取输入内容
    Java数据类型的转换
    Java十进制数转二进制的方法
    Java查看项目目录以及导入项目
    ios 证书申请和发布流程
    Spring 注解大全
    Spring Boot开发Web应用
    Spring Boot中Web应用的统一异常处理
    Spring Boot中使用AOP统一处理Web请求日志
    Spring Boot属性配置文件详解
  • 原文地址:https://www.cnblogs.com/wangyang0210/p/14540428.html
Copyright © 2011-2022 走看看