two sum
2014-05-16 13:48
218 查看
Question 1:
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
Answer:
1.排序后,用两个指针从前后开始查。时间复杂度o(nlgn),结果是over time
快排:
public static void quickSort(int[] sum, int begin, int end) {
int left = begin;
int right = end;
int base = sum[end];
while (left < right){
while (left < right && sum[left] <= base) {
++left;
}
sum[right] = sum[left];
while (left < right && sum[right] >= base) {
--right;
}
sum[left] = sum[right];
}
sum[left] = base;
quickSort(sum, begin, left - 1);
quickSort(sum, left + 1, end);
}
2、借助于Hash表,用空间换时间。
hash可以用o(1)的复杂度判断一个元素是否在hashmap里。将数据中的数据保存在hash表中,判断target-now是否在target中出现过。
code:
AC
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
Answer:
1.排序后,用两个指针从前后开始查。时间复杂度o(nlgn),结果是over time
快排:
public static void quickSort(int[] sum, int begin, int end) {
int left = begin;
int right = end;
int base = sum[end];
while (left < right){
while (left < right && sum[left] <= base) {
++left;
}
sum[right] = sum[left];
while (left < right && sum[right] >= base) {
--right;
}
sum[left] = sum[right];
}
sum[left] = base;
quickSort(sum, begin, left - 1);
quickSort(sum, left + 1, end);
}
2、借助于Hash表,用空间换时间。
hash可以用o(1)的复杂度判断一个元素是否在hashmap里。将数据中的数据保存在hash表中,判断target-now是否在target中出现过。
code:
public class Solution { public int[] twoSum(int[] numbers, int target) { HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); int result[] = new int[2]; for (int i = 0; i < numbers.length; ++i) { int now = numbers[i]; int dis = target - now; if (map.containsKey(dis)) { int index = map.get(dis) + 1; result[0] = index; result[1] = i + 1; break; } else { map.put(now, i); } } return result; } }
AC
相关文章推荐
- Two sum
- LeetCode-Two Sum
- Leetcode#1 Two Sum
- LeetCode------Two Sum
- Two Sum
- [LeetCode]Two Sum
- [Leetcode 1, Medium] Two sum
- 面试题:Two Sum
- 1 Two Sum
- Leetcode 1:Two Sum
- LeetCode:Two Sum
- LeetCode_Two Sum
- LeetCode OJ 系列之1 Two Sum --Python
- leetcode刷题日记——Two Sum
- Two Sum
- 1、Two Sum
- Two sum 在数组中寻找和为指定值的两个数
- Leetcode #1 Two Sum 解题小结
- [leetcode]1 Two Sum
- 1. Two Sum