每日算法:167. 两数之和 II - 输入有序数组

244 阅读1分钟

难度:简单

给定一个已按照 升序排列  的整数数组 numbers ,请你从数组中找出两个数满足相加之和等于目标数 target 。

函数应该以长度为 2 的整数数组的形式返回这两个数的下标值。numbers 的下标 从 1 开始计数 ,所以答案数组应当满足 1 <= answer[0] < answer[1] <= numbers.length 。

你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素

解题思路

由于给定的数组已经排好序了,那么可以考虑从该数组的两边开始着手,如果大于 target,那么表示两边的数字选的偏大了,则最大一边,也就是右边向左边移动,反之左边向右移动。

题解

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

测试

TwoSumII twoSumII = new TwoSumII();

@Test
public void test_case1() {
    int[] actual = twoSumII.twoSum(new int[]{2, 7, 11, 15}, 9);
    Assertions.assertArrayEquals(new int[]{1, 2}, actual);
}

@Test
public void test_case2() {
    int[] actual = twoSumII.twoSum(new int[]{2, 3, 4}, 6);
    Assertions.assertArrayEquals(new int[]{1, 3}, actual);
}

@Test
public void test_case3() {
    int[] actual = twoSumII.twoSum(new int[]{-1, 0}, -1);
    Assertions.assertArrayEquals(new int[]{1, 2}, actual);
}