1、Two Sum

Leetcode Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

思路:

用一个HashMap存储元素。

以【2,7,11,15】 target=9为例。从2开始扫描整个数组,差值9-2=7,此时7 不在HashMap中,就把2和2的下标0添加到HashMap中。此时HashMap中的元素为【(2,0)】。

下一步扫描到7,差值9-7=2,发现2已经在HashMap中,就直接返回2的下标0 和7的下标1。

整个算法的时间复杂度为O(n),就是扫描一遍数组的时间。

再以【3,3】 target = 6为例。首先扫描3,差值为6-3=3。此时3不在HashMap中,就把(3,0)添加到HashMap中。然后扫描第二个3,差值6-3=3,发现3在HashMap中,则直接返回(0,1)。

总结:

  • 如果target与当前值的差值不在HashMap中,则将当前值与下标存放在HashMap里。注意,值是key,下标是value
  • 如果target与当前值的差值在HashMap中,则返回结果。
class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < nums.length; i++) {
            int diff = target - nums[i];
            if(map.containsKey(diff)) {
                return new int[] {map.get(diff), i};
            }
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }

}

注:学渣心里苦,不要学楼主,平时不努力,考试二百五,哭~

这里写图片描述

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值