1. 程式人生 > >leetcode:(167)Two Sum II(java)

leetcode:(167)Two Sum II(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.

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.

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.

 

題目:

       在有序陣列中找出兩個數,使它們的和為 target。

解題思想:

      使用雙指標,一個指標指向值較小的元素,一個指標指向值較大的元素。指向較小元素的指標從頭向尾遍歷,指向較大元素的指標從尾向頭遍歷。

  • 如果兩個指標指向元素的和  等於 target,那麼返回兩個指標所指陣列的下標+1;
  • 如果 兩個指標指向元素的和大於 target,移動較大的元素,使 和變小一些;
  • 如果 兩個指標指向元素的和 小於 target,移動較小的元素,使 和 變大一些。

程式碼:

package Leetcode_Github;

public class TwoPoints_TwoSumII_167_1031 {
    public int[] twoSum(int[] numbers, int target) {
        int[] result = new int[2];
        if (numbers.length < 2) {
            return result;
        }

        int length = numbers.length;
        int small = numbers[0];
        int big = numbers[length-1];
        for (int i = 0, j = length-1; i < numbers.length && j > 0 && j > i; ) {

            if (small + big == target) {
                result[0] = i + 1;
                result[1] = j + 1;
                break;
            }
            if (small + big > target) {
                j--;
            }
            if (small + big < target) {
                i++;
            }
            small = numbers[i];
            big = numbers[j];
        }
        return result;
    }

測試函式:
    public static void main(String[] args) {
        int[] array = {2, 7, 11, 15};
        int target = 9;
        TwoPoints_TwoSumII_167_1031 test = new TwoPoints_TwoSumII_167_1031();
        int[] result = test.twoSum(array, target);
        System.out.println(result[0] + " " + result[1]);
    }
}