LintCode 56. Two Sum 原创Java参考解答
问题描述
http://www.lintcode.com/en/problem/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.
Notice
You may assume that each input would have exactly one solution
Example
numbers=[2, 7, 11, 15]
, target=9
return [1, 2]
解题思路
Two Sum是一道非常高频出现的算法面试题。题目是在数组中寻找两个和为target的数。
O(N)的做法。引入一个HashMap,key为target与数组访问过的每个元素的差值,value为数组中该元素的位置。在数组中每次走一个位置,就检查HashMap,看该位置这个数是否就是前面某个数需要找来拼成target的数。不是的话,就把这个数需要的差值和该位置索引在HashMap里面登记一下。
题目中值得注意的:
- 返回的答案索引不是以0为开始的
- 数组并非排序数组
参考代码
public class Solution { /* * @param numbers : An array of Integer * @param target : target = numbers[index1] + numbers[index2] * @return : [index1 + 1, index2 + 1] (index1 < index2) */ public int[] twoSum(int[] numbers, int target) { if (numbers == null || numbers.length == 0) { return new int[0]; } HashMap<Integer, Integer> complement = new HashMap<>(); for (int i = 0; i < numbers.length; i++) { if (complement.containsKey(numbers[i])) { int[] result = new int[2]; result[0] = complement.get(numbers[i]) + 1; result[1] = i + 1; return result; } complement.put(target - numbers[i], i); } return new int[0]; } }