刷leetcode:Two Sum

题号:1  题目

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

求数组中两个数之和为定值的两个数的index,之前我们最常见数组中求两个数之和为定值的两个数。

类似的题目在《编程之美》中也出现过(求两个数之和为N+1的两个数),July大神在他的 博客中详细讲述过这个问题。

这里需要注意的是,题目要求的是要返回两个数的index,是以上问题的一个扩展。

解析思路还是一样的,由于数组是无序的,在排序的过程中会破坏数组的index信息,我们还需要额外的空间存贮index信息,这里采用Hash的方式直接解决。


实现的代码很简单,这里面有一个问题需要说一下,我们通常的想法是遍历数组,然后把target和数组元素的差值存入一个HashMap中,这样我们就可以通过差值作为key进行查找了。但是,如果数组中含有相同元素以上逻辑就崩溃了。所以,采用一边遍历一边插值的方式实现。


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


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值