美文网首页
leetcode 01.两数之和

leetcode 01.两数之和

作者: 点二二四 | 来源:发表于2018-09-16 00:35 被阅读0次

题目描述:

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

示例:

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

代码:

import java.util.HashMap;

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (map.containsKey((complement))) {
                return new int[] {map.get(complement), i};
            }
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}

相关文章

  • leetcode 01.两数之和

    题目描述: 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只对应一种答案,且同样...

  • 【LeetCode通关全记录】1. 两数之和

    【LeetCode通关全记录】1. 两数之和 题目地址:1. 两数之和[https://leetcode-cn.c...

  • 双指针

    两数之和 click here for leetcode detail[https://leetcode-cn.c...

  • 纯C手撕leetcode-基本数据结构-hash table

    Hash table纯C实现两数之和和Hashtable 三数之和https://leetcode-cn.com/...

  • 01. 两数之和

    https://www.bilibili.com/video/BV1wA411b7qZ 题目 给定一个整数数组 n...

  • 01.两数之和

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

  • 01.两数之和

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

  • 01.两数之和

    01.两数之和 问题引入: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的...

  • [LeetCode] TwoSum两数之和

    [LeetCode] TwoSum两数之和 Given an array of integers, returni...

  • LeetCode 专题 :双指针

    LeetCode 第 167 题:两数之和 II - 输入有序数组 传送门:167. 两数之和 II - 输入有序...

网友评论

      本文标题:leetcode 01.两数之和

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