美文网首页
[力扣] 1. 两数之和

[力扣] 1. 两数之和

作者: Hunsmore | 来源:发表于2020-03-03 20:56 被阅读0次

链接:https://leetcode-cn.com/problems/two-sum

题目

[简单] 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例

给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

class Solution {
    public int[] twoSum(int[] nums, int target) {
        //target和num的差是否已被索引
        //一次遍历即可
        Map<Integer,Integer> map = new HashMap<>();
        for(int i=0;i<nums.length;i++){
            int num = nums[i];
            int m = target - nums[i];
            if(map.containsKey(m)){
                return new int[]{map.get(m),i};
            }
            map.put(num,i);
        }
        return null;
    }
}

相关文章

  • [力扣] 1. 两数之和

    链接:https://leetcode-cn.com/problems/two-sum 题目 [简单] 给定一个整...

  • 【力扣】1. 两数之和

    题目 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回...

  • 力扣1. 两数之和

    题目 给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target ...

  • 力扣题库_#1.两数之和

    题目 给定一个整数数组nums和一个目标值target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的...

  • 力扣-两数之和

    给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的...

  • ATRS第1周

    ATRS Algorithm算法题: 两数之和 - 力扣 (LeetCode) ``` function twoS...

  • 力扣刷题——1. 两数之和

    题目 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回...

  • 力扣百题-1. 两数之和

    比较简单,用一个Map记录曾经遍历过的元素,计算出差值,如果符合,直接返回结果,时间复杂度O(n),空间复杂度O(n)

  • twoSum问题的核心思想

    读完本文,你可以去力扣拿下如下题目: 1.两数之和[https://leetcode-cn.com/problem...

  • 面试问到的算法

    快排,冒泡区别,两数之和,反转链表,判断环,数组中重复数组350 力扣 力扣26题

网友评论

      本文标题:[力扣] 1. 两数之和

      本文链接:https://www.haomeiwen.com/subject/aujllhtx.html