-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSumIiInputArrayIsSorted.java
More file actions
68 lines (65 loc) · 2.02 KB
/
TwoSumIiInputArrayIsSorted.java
File metadata and controls
68 lines (65 loc) · 2.02 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
//给你一个下标从 1 开始的整数数组 numbers ,该数组已按 非递减顺序排列 ,请你从数组中找出满足相加之和等于目标数 target 的两个数。如果设这
//两个数分别是 numbers[index1] 和 numbers[index2] ,则 1 <= index1 < index2 <= numbers.
//length 。
//
// 以长度为 2 的整数数组 [index1, index2] 的形式返回这两个整数的下标 index1 和 index2。
//
// 你可以假设每个输入 只对应唯一的答案 ,而且你 不可以 重复使用相同的元素。
//
// 你所设计的解决方案必须只使用常量级的额外空间。
//
// 示例 1:
//
//
//输入:numbers = [2,7,11,15], target = 9
//输出:[1,2]
//解释:2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。返回 [1, 2] 。
//
// 示例 2:
//
//
//输入:numbers = [2,3,4], target = 6
//输出:[1,3]
//解释:2 与 4 之和等于目标数 6 。因此 index1 = 1, index2 = 3 。返回 [1, 3] 。
//
// 示例 3:
//
//
//输入:numbers = [-1,0], target = -1
//输出:[1,2]
//解释:-1 与 0 之和等于目标数 -1 。因此 index1 = 1, index2 = 2 。返回 [1, 2] 。
//
//
//
//
// 提示:
//
//
// 2 <= numbers.length <= 3 * 10⁴
// -1000 <= numbers[i] <= 1000
// numbers 按 非递减顺序 排列
// -1000 <= target <= 1000
// 仅存在一个有效答案
//
//
// 👍 1317 👎 0
package leetcode.editor.cn;
public class TwoSumIiInputArrayIsSorted{
public static void main(String[] args) {
Solution solution = new TwoSumIiInputArrayIsSorted().new Solution();
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int[] twoSum(int[] numbers, int target) {
int l = 0, r = numbers.length - 1;
while (l < r) {
int sum = numbers[l] + numbers[r];
if (sum == target) break;
if (sum > target) r--;
else l++;
}
return new int[]{l+1, r+1};
}
}
//leetcode submit region end(Prohibit modification and deletion)
}