本文共 1009 字,大约阅读时间需要 3 分钟。
为了解决从一个按升序排列的整数数组中找出两个数,使它们的和等于给定目标值的问题,我们可以使用双指针法。这种方法高效且简洁,能够在O(n)时间内找到答案。
双指针法的基本思想是使用两个指针,分别从数组的两端开始移动。左指针从数组的开始移动,右指针从数组的末尾移动。每次计算这两个指针指向的数的和:
这种方法利用了数组的有序性,能够在较少的步骤内找到正确的配对。
class Solution { public int[] twoSum(int[] numbers, int target) { int low = 0; int high = numbers.length - 1; while (low < high) { int sum = numbers[low] + numbers[high]; if (sum == target) { return new int[]{low + 1, high + 1}; } else if (sum < target) { low++; } else { high--; } } return new int[]{-1, -1}; // 根据题目,每个输入都有唯一解,这里可以不处理 }}
low
指针初始化为0,high
指针初始化为数组长度减一。low
小于high
时,继续循环。low
和high
指针指向的数的和。low
指针右移。high
指针左移。这种方法在处理数组时,时间复杂度为O(n),空间复杂度为O(1),非常高效。
转载地址:http://gofmz.baihongyu.com/