Array
Two Pointers
Binary Search
Description:
Given an array of integers that is already sorted in ascending order, 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 and you may not use the same element twice.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
其实我是只会最暴力的直接穷举法的,参考了July大神的文章,搞懂了这题tag里的Two Pointers
到底是什么意思。在这道题里,指的就是用两个指针在首尾分别往中间扫描,通过条件来判定哪一边的指针需要移动。
my Solution:
public class Solution {
public int[] twoSum(int[] numbers, int target) {
int n = numbers.length;
int[] output = new int[2];
int i = 0, j = n-1;
while (i < j) {
if (numbers[i] + numbers[j] > target) {
j--;
} else if (numbers[i] + numbers[j] < target) {
i++;
} else {
output[0] = ++i;
output[1] = ++j;
break;
}
}
return output;
}
}
对于这道经典题,July提出了好几种解法,分别为:
- 二分,时间复杂度$O(NlogN)$ 空间复杂度$O(1)$
- 扫描一遍X-numbers[i]映射到一个hash表,Discuss里有人用这种方法,其实是二叉树查找的思想,不过时间复杂度虽然变为$O(N)$,但由于要创建hash表,空间复杂度为$O(N)$
- 两指针从两端向中间扫描,就是Solution的解法