您的位置:首页 > 其它

LeetCode_Two Sum

2015-04-26 09:55 302 查看


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.
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(n2) runtime, O(1) space – Brute force:

The brute force approach is simple. Loop through each element x and find if there is another value that equals to target – x. As finding another value requires looping through the rest of array, its runtime complexity is O(n2).


O(n) runtime, O(n) space – Hash table:

We could reduce the runtime complexity of looking up a value to O(1) using a hash map that maps a value to its index.

总之就是,时间换空间 and 空间换时间!

java使用hashtable的实现:

public static int[] twoSum(int[] nums, int target) {
// key为数组中的那个数,value为那个数的序号
Hashtable<Integer, Integer> ht = new Hashtable<Integer, Integer>();
int[] res = new int[2];
for(int i=0; i<nums.length; i++){
// 对每一个数边放边查找,时间复杂度控制在O(n),牺牲了空间O(n)
if(ht.get(target-nums[i]) != null){
res[0] = ht.get(target-nums[i]) + 1;
res[1] = i+1;
}else{
ht.put(nums[i], i);
}
}
return res;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 leetcode hashtable