- 题目链接:Leetcode :167. Two Sum II - Input array is sorted (Easy)
- 题目描述:在有序数组中找出两个数,使它们的和为 target。
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
- 解
package 双指针;
/**
* 题目描述:在有序数组中找出两个数,使它们的和为 target。
* Input: numbers={2, 7, 11, 15}, target=9
* Output: index1=1, index2=2
* @author 林博弈
*
*/
public class One_Sum {
public static void main(String[] args) {
int[] numbers = {2,7,11,15};
sum(numbers, 9);
}
public static void sum(int[] arr,int target){
int start = 0;
int end = arr.length-1;
int sum = arr[start]+arr[end];
while(sum!=target&&start<end){
if(sum>target)end--;
else if(sum<target)start++;
sum = arr[start]+arr[end];
}
System.out.println("index1="+(start+1)+" index2="+(end+1));
}
public static int[] twoSum(int[] numbers, int target) {
int i = 0, 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) {
i++;
} else {
j--;
}
}
return null;
}
}