LeetCode - Two Sum

问题连接:https://oj.leetcode.com/problems/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.


API接口: public int[] twoSum(int[] numbers, int target)


这题已经是很老很经典的题了,在我三年前开始找工作的时候这题目就很流行了。

主要解题思路有二,一是用哈希表存遍历的值,一次遍历循环即可。key放的是target - number[i], value放的是index。

循环扫的时候对比是否存在当前number[i]的键,也就是找0 <= j < i的范围里,是否存在target - number[j] = number[i]. 找得到的话即可范围答案,没找到继续放入(target - number[i], i )的键值对,直到找到为止。时间O(n), 空间O(n)

代码如下:

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

第二种解题思路基于排序,但因为本题要求返回的是index,所以返回起来比较麻烦。会在后面的另一题放出相对的代码。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值