1. 程式人生 > >leetcode Two Sum II - Input array is sorted

leetcode Two Sum II - Input array is sorted

Two Sum II - Input array is sorted 題目:https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/

解題思路:

在一個有序陣列中,尋找兩個數的和等於指定的元素的值。

使用兩個指標,一個指向第一個元素,一個指向最後一個元素。

如果他們的和大於目標值,指定最後一個元素的指標向前移動。

如果他們的和小於指定的目標值,指向第一個元素的指標向後移動。

public static void main(String[] args) {
		int[] arr={2, 7, 11, 15};
		int target=9;
		int[] ints = twoSum(arr, target);
		System.out.println(Arrays.toString(ints));
	}

	public  static int[] twoSum(int[] numbers, int target) {
		int[] arr=new int[2];
		int i=0;
		int j=numbers.length-1;
		while(i<j){
			if(numbers[i]+numbers[j]<target){
				i++;
			}else if(numbers[i]+numbers[j]>target){
				j--;
			}else{
				arr[0]=i+1;
				arr[1]=j+1;
				return arr;
			}
		}
		return null;
	}