您的位置:首页 > 其它

Two Sum

2015-06-10 20:56 225 查看

1. Question

给一整数数组,找两个数,使其和正好是给定值。函数 twoSum应当返回两个数的索引,且index1小于index2。索引不是从0开始的。

假设每个输入都正好有一个解。

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


2. Solution

最优方案时间复杂度O(n)

2.1 O(n2) solution

用两个循环遍历所有数对,找到符合要求的。

2.2 O(nlogn) solution

方案一:采用二叉搜索

数组按升序排序(采用map存储数组值和索引)

遍历数组,假设每个值是两个数的其中一个值,采用二叉搜索查找另一个值。

import java.util.Hashtable;

public class Solution {
//when using map structure, we don't need to sort the array
public int[] twoSum( int[] numbers, int target ){
Hashtable< Integer, Integer > num = new Hashtable< Integer, Integer >();
for( int i=0; i< numbers.length; i++ ){
if( num.get( numbers[i]) == null )
num.put(numbers[i], i);
Integer j = num.get( target - numbers[i]);
if( j!=null && j < i )
return new int[] { j.intValue()+1, i+1 };
}
return null;
}
}


map
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: