您的位置:首页 > 编程语言 > Java开发

[leetcode NO.1] Two Sum (JAVA)

2014-09-03 22:20 537 查看
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
这个题目很具有代表性,大家的想法可能是对每个a[i] 在 n个数组中找 target - a[i], 每个数需要O(N),总共这个方法需要O(n2)时间, 其实在这个基础上稍微修改下即可,我们考虑一种利用特定数据结构来查询特定数据使时间变为O(1)的算法,众所周知, 只有hash表才能使查询为O(1), 所以这个题目,我们采用hashtable,
具体思路如下:我们遍历数组a, 对每个数组a[i] , 如果 target - a[i] 不在hashtable中, 则将a[i] 和 i 存入hashtable中, 如果target - a[i]在数组中说明我们已经找到, 这时将其从hashtable中get出来就ok了。
具体代码:
import java.util.Hashtable;
public class Solution {
public int[] twoSum(int[] numbers, int target) {
int a[] = {0,0};
Hashtable<Integer, Integer> ht = new Hashtable<Integer, Integer>();
for(int i = 0; i < numbers.length; i++)
{
if(ht.containsKey(numbers[i]))
{
int j = ht.get(numbers[i]);
a[0] = j;
a[1] = i + 1;
return a;
}
else
{
ht.put(target - numbers[i], i + 1);
}
}
return a;
}
}


细节问题: 存入hashtable(key, value)的key和value要搞清楚, 因为get(key)只能得到value
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: