java two sum 讲解_【LeetCode】TwoSum-Java

题目: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

第一想法,拿到输入后,暴力搜索,时间复杂度为O(n*n),很简单,但是会出现超时错误。

显然,时间复杂度需要再降低才行。看过别人的题解后,使用了Java中的Map,利用HashMap,存储数组中的值和Index,由于HashMap中查询键值对的开销是固定的,因此在性能上可以得到很大的提升。

对输入先构建HashMap,对于HashMap需要考虑,用什么做key,什么做value。题目中要求求两者的和,显然,用数组值做index来检索index是合理恰当的设置。遍历数组,构建这样的HashMap。

第二遍遍历数组,对每个值value_i,在HashMap中查找是否存在对应的target-value_i,若存在,根据这个key找到对应的value值,即得到要找的两个index。由于数组遍历的顺序是由小到大,因此得到的map中的index2必然大于index1。

需要注意的一个小细节是,在HashMap中进行查找时,要避免出现index1和index2相等的情况。

public class Solution {

public int[] twoSum(int[]

numbers, int target) {

int[] res = new int[2];

Map map = new HashMap();

for(int i = 0; i < numbers.length; i++){

map.put(numbers[i], i);

}

for(int i = 0; i < numbers.length; i++){

int gap = target - numbers[i];

if(map.get(gap)!= null && map.get(gap)!= i){

res[0] = i+1;

res[1] = map.get(gap) + 1;

break;

}

}

return res;

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值