-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path00167-two_sum_II.java
More file actions
37 lines (30 loc) · 910 Bytes
/
00167-two_sum_II.java
File metadata and controls
37 lines (30 loc) · 910 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// 167: Two Sum II
// https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
class Solution {
// SOLUTION
public int[] twoSum(int[] numbers, int target) {
int l = 0;
int r = numbers.length - 1;
int[] result = new int[2];
while (l<r) {
int s = numbers[l] + numbers[r];
if (s==target) {
result[0] = l+1;
result[1] = r+1;
break;
}
else if (s<target) l++;
else r--;
}
return result;
}
public static void main(String[] args) {
Solution o = new Solution();
// INPUT
int[] numbers = {2,7,11,15};
int target = 9;
// OUTPUT
var result = o.twoSum(numbers, target);
System.out.print("["); for (var v : result) System.out.print(v+" "); System.out.println("\b]");
}
}