博客
关于我
【leetcode】二分查找-两数之和 II - 输入有序数组
阅读量:659 次
发布时间:2019-03-15

本文共 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时,继续循环。
  • 计算和:计算lowhigh指针指向的数的和。
  • 判断和
    • 如果和等于目标值,返回这两个数的下标(各自加1)。
    • 如果和小于目标值,说明需要更大的数,low指针右移。
    • 如果和大于目标值,说明需要更小的数,high指针左移。
  • 返回默认值:虽然题目保证有唯一解,但为了完整性,返回默认值-1,-1。
  • 这种方法在处理数组时,时间复杂度为O(n),空间复杂度为O(1),非常高效。

    转载地址:http://gofmz.baihongyu.com/

    你可能感兴趣的文章
    npm install 权限问题
    查看>>
    npm install报错,证书验证失败unable to get local issuer certificate
    查看>>
    npm install无法生成node_modules的解决方法
    查看>>
    npm install的--save和--save-dev使用说明
    查看>>
    npm node pm2相关问题
    查看>>
    npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
    查看>>
    npm run build报Cannot find module错误的解决方法
    查看>>
    npm run build部署到云服务器中的Nginx(图文配置)
    查看>>
    npm run dev 和npm dev、npm run start和npm start、npm run serve和npm serve等的区别
    查看>>
    npm run dev 报错PS ‘vite‘ 不是内部或外部命令,也不是可运行的程序或批处理文件。
    查看>>
    npm scripts 使用指南
    查看>>
    npm should be run outside of the node repl, in your normal shell
    查看>>
    npm start运行了什么
    查看>>
    npm WARN deprecated core-js@2.6.12 core-js@<3.3 is no longer maintained and not recommended for usa
    查看>>
    npm 下载依赖慢的解决方案(亲测有效)
    查看>>
    npm 安装依赖过程中报错:Error: Can‘t find Python executable “python“, you can set the PYTHON env variable
    查看>>
    npm.taobao.org 淘宝 npm 镜像证书过期?这样解决!
    查看>>
    npm—小记
    查看>>
    npm上传自己的项目
    查看>>
    npm介绍以及常用命令
    查看>>