【双指针】167. 两数之和 II - 输入有序数组【中等】

两数之和 II - 输入有序数组

  • 给你一个下标从 1 开始的整数数组 numbers ,该数组已按 非递减顺序排列 ,请你从数组中找出满足相加之和等于目标数 target 的两个数。

  • 如果设这两个数分别是 numbers[index1] 和 numbers[index2] ,则 1 <= index1 < index2 <= numbers.length 。

  • 以长度为 2 的整数数组 [index1, index2] 的形式返回这两个整数的下标 index1 和 index2。

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

你所设计的解决方案必须只使用常量级的额外空间

示例 1:

输入:numbers = [2,7,11,15], target = 9
输出:[1,2]
解释:2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。返回 [1, 2] 。

解题思路

  • 由于数组已按非递减顺序排列,可以使用双指针技巧来寻找两个数之和等于目标数。
  • 首先将两个指针分别指向数组的开头和结尾,然后逐步向中间移动, 根据两个指针指向的数的和与目标数的大小关系来调整指针的位置。

Java实现

public class TwoSumII {

    public int[] twoSum(int[] numbers, int target) {
        int left = 0, right = numbers.length - 1;
        while (left < right) {
            int sum = numbers[left] + numbers[right];
            if (sum == target) {
                return new int[]{left + 1, right + 1};
            } else if (sum < target) {
                left++;
            } else {
                right--;
            }
        }
        return new int[]{-1, -1}; // 如果找不到满足条件的两个数,则返回 [-1, -1]
    }

    public static void main(String[] args) {
        TwoSumII twoSumII = new TwoSumII();
        int[] numbers1 = {2, 7, 11, 15};
        int target1 = 9;
        System.out.println("Test Case 1:");
        System.out.println("Numbers: [2, 7, 11, 15], Target: 9");
        int[] result1 = twoSumII.twoSum(numbers1, target1);
        System.out.println("Indices: [" + result1[0] + ", " + result1[1] + "]"); // Expected: [1, 2]

        int[] numbers2 = {2, 3, 4};
        int target2 = 6;
        System.out.println("\nTest Case 2:");
        System.out.println("Numbers: [2, 3, 4], Target: 6");
        int[] result2 = twoSumII.twoSum(numbers2, target2);
        System.out.println("Indices: [" + result2[0] + ", " + result2[1] + "]"); // Expected: [1, 3]
    }
}

时间空间复杂度

时间复杂度: 使用双指针遍历数组,时间复杂度为 O(n),其中 n 是数组的长度。
空间复杂度: 使用了常量级的额外空间,空间复杂度为 O(1)。

  • 8
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值