[LeetCode] Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

这题第二次做,结果一下还没成功,比较二的自作聪明的写了if(numbers[i]>target) continue;

其实这样一来就打破了map里原数组的顺序, e.g [-3.4,3,90] target=0 的test case中就出错了。

还有就是map.put()的时机,e.g. [3,4,2,7] target=6, 我最开始是直接在for循环里初始就map.put(numbers[i],i)了。这样在后面的判断就成功了,于是

返回了两个[1,1], 而不是[2,3]. 后来还在考虑index大小的问题。

e.g. [0,4,3,0] 如果我们一开始就put进去,那么到第二个0的时候,map中的value是[0=4,4=2,3=3] 就覆盖掉之前的结果了. 所以最好是先判断,再存入.


    public int[] twoSum(int[] numbers, int target) {
        int[] res=new int[2];
        if(numbers.length==0) return res;
        HashMap<Integer, Integer> map= new HashMap<>();
        for(int i=0;i<numbers.length;i++){
 
            if(map.containsKey(target-numbers[i])){
                res[0]=map.get(target-numbers[i])+1;
                res[1]=i+1;
                return res;
            }
                map.put(numbers[i],i);
        }
        return res;
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值