博客
关于我
【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/

    你可能感兴趣的文章
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
    查看>>
    No module named 'crispy_forms'等使用pycharm开发
    查看>>
    No module named 'pandads'
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    no session found for current thread
    查看>>
    No static resource favicon.ico.
    查看>>
    no such file or directory AndroidManifest.xml
    查看>>
    No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
    查看>>
    NO.23 ZenTaoPHP目录结构
    查看>>
    no1
    查看>>
    NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
    查看>>