More:【目錄】LeetCode Java實現html
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/java
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.less
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.post
Note:ui
Example:url
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.
refer to 和爲s的兩個數字spa
public int[] twoSum(int[] num, int target) { int i=0, j=num.length-1; while(i<j){ if(num[i]+num[j]<target) i++; else if(num[i]+num[j]>target) j--; else return new int[]{i+1,j+1}; } return null; }
Time complexity : O(n)
code
Space complexity : O(1)htm
1.The use of two pointers.blog
More:【目錄】LeetCode Java實現