前言
歡迎關注我的 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電子書~