前言
欢迎关注我的 Github,如果觉得有帮助,请点个 star
哟,目前主要在更 leetcode题解(Java版)
和 剑指offer题解(Java版)
,可以点个star
。
文本已收录至我的GitHub仓库,欢迎Star:awesome-java-notes
167. Two Sum II - Input array is sorted
题目描述 给定一个已经从小到大排好序的整型数组,找到其中的两个数,使它们的和等于给定的目标值。函数 twoSum 应返回两个数的索引,以便它们加起来等于目标值,其中 index1 必须小于 index2。
Note:
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.
Example
- Input: numbers = [2,7,11,15], target = 9
- Output: [1,2]
- Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
解答
使用双指针来解决,其中一个指针从头到尾开始遍历,指向值较小的值;另一个指针从尾到头开始遍历,指向值较大的值。
- 两个指针所指向元素之和 sum 等于给定值 target,即为所求
- 两个指针指向元素之和 sum 大于给定值 target,则向前移动较大元素,使 sum 减小一些
- 两个指针指向元素之和 sum 小于给定值 target,则向后移动较小元素,使 sum 变大一些
class Solution {
public int[] twoSum(int[] numbers, int target) {
int i = 0;
int j = numbers.length - 1;
while (i < j) {
int sum = numbers[i] + numbers[j];
if (sum == target) {
return new int[] {i + 1, j + 1};
} else if (sum > target) {
j --;
} else {
i ++;
}
}
return null;
}
}
结语
如果你同我一样想要征服数据结构与算法、想要刷 LeetCode,欢迎关注我 GitHub 上的 LeetCode 题解:awesome-java-notes
欢迎扫码关注我的公众号「蜗牛永动机」,回复 1024 免费获取精心整理的业内工人的经典IT电子书~