天增的博客
首页
博客
  • 分布式解决方案
  • Java并发工具包
  • redis
  • LeetCode
  • 系统设计
  • JVM体系
Github (opens new window)
Rss (opens new window)
  • zh-CN
  • en-US
首页
博客
  • 分布式解决方案
  • Java并发工具包
  • redis
  • LeetCode
  • 系统设计
  • JVM体系
Github (opens new window)
Rss (opens new window)
  • zh-CN
  • en-US
  • LeetCode
  • 双指针
    • 26.删除有序数组中的重复项
    • 80.删除有序数组中的重复项2
    • 27.移除元素
    • 167.两数之和 II - 输入有序数组
    • 283.移动零
    • 125.验证回文串
    • 344.反转字符串
    • 11.盛最多水的容器
    • 345.反转字符串中的元音字母
  • topic
  • LeetCode
  • 双指针
  • 两数之和 II - 输入有序数组
2022-05-25

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

# 167.两数之和 II - 输入有序数组

LeetCode链接: https://leetcode.cn/problems/two-sum-ii-input-array-is-sorted/solution/yi-zhang-tu-gao-su-ni-on-de-shuang-zhi-zhen-jie-fa/ (opens new window)

题目描述:在有序数组中找出两个数,使它们的和为 target。

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

一个指针指向值较小的元素,一个指针指向值较大的元素。

指向较小元素的指针从头向尾遍历,指向较大元素的指针从尾向头遍历。

  • 如果两个指针指向元素的和 sum == target,那么得到要求的结果;
  • 如果 sum > target,移动较大的元素,使 sum 变小一些;
  • 如果 sum < target,移动较小的元素,使 sum 变大一些。

数组中的元素最多遍历一次,时间复杂度为 O(N)。只使用了两个额外变量,空间复杂度为 O(1)。

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

复杂度分析

  • 时间复杂度:$O(n)$,其中 $n$ 是数组的长度。两个指针移动的总次数最多为 $n$ 次。
  • 空间复杂度:$O(1)$。

‍

最近更新
01
以 root 身份启动 transmission-daemon
12-13
02
Debian系统安装qbittorrent-nox
12-09
03
LXC Debain12安装zerotier并实现局域网自动nat转发
07-29
更多文章>
Theme by Vdoing | Copyright © 2015-2024 天增 | 苏ICP备16037388号-1
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式