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]);
    }
}

猜你喜欢

转载自blog.csdn.net/Sunshine_liang1/article/details/83583261