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;
}
相关文章推荐
- Two Sum--LeetCode
- [leetcode]: 1. Two Sum
- 【LeetCode】第1题: Two Sum
- Leetcode 1. Two Sum
- leetcode之Two Sum
- LeetCode - Two Sum 完整代码(GO)
- 【leetcode】【1】Two Sum
- leetcode No.1 Two Sum
- leetcode------第一题 Two Sum
- LeetCode-Two Sum
- leetcode-Two Sum
- LeetCode 1.Two Sum
- leetcode 刷题题解(c++) 1.Two Sum (hash表,排序+二分查找)
- [leetcode 1] Two Sum
- LeetCode 01 Two Sum
- leetcode之Two Sum
- leetcode 1 -- Two Sum
- LeetCode|Two Sum
- [Leetcode]之一《two sum》解题报告
- [LeetCode] Two Sum