TwoSumII_InputArrayIsSorted [source code]
public class TwoSumII_InputArrayIsSorted {
public int[] twoSum(int[] numbers, int target) {
int head = 0, tail = numbers.length - 1;
while (head < tail) {
if (numbers[head] + numbers[tail] == target) break;
if (numbers[head] + numbers[tail] > target) tail--;
else head++;
}
int[] res = new int[2];
res[0] = head + 1;
res[1] = tail + 1;
return res;
}
}
这个题目也是不陌生了, 速度是1ms. 之前在 PDF 上面总结的时候, 好像说是, 在 sorted 的题目里面,
2pointers 的思路格外常见;
Problem Description
Given an array of integers that is already sorted in asctailing 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
Difficulty:Easy
Category:Algorithms
Acceptance:47.14%
Contributor: LeetCode
Topics:
Array Two Pointers Binary Search
You might like:
(E) Two Sum
Company:
Amazon