算法 Java Leetcode Golang

Return indices of the two numbers added up to the target.

Question

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.
See it on Leetcode

1
2
3
For example:
Input numbers = [2, 7, 11, 15], with target = 9
It should return [1, 2]

Hint

  1. 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.
  2. Your returned answers (both index1 and index2) are not zero-based.
  3. Each input would have exactly one solution.

Solution in Java, C++ and Javascript

  • java
  • cpp
  • js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Solution {
public int[] twoSum(int[] numbers, int target) {
int left = 0, right = numbers.length - 1;
while (left < right) {
if (numbers[left] + numbers[right] == target) {
return new int[]{left + 1, right + 1};
} else if (numbers[left] + numbers[right] < target) {
left++;
} else {
right--;
}
}
throw new IllegalArgumentException("No two sum solution");
}
}

Solution in Golang

  • go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func twoSum(numbers []int, target int) []int {
left := 0
right := len(numbers) - 1
for left < right {
switch {
case numbers[left] + numbers[right] > target:
right--
case numbers[left] + numbers[right] < target:
left++
default:
return []int{left + 1, right + 1}
}
}
return []int{0, 0}
}