LeetCode 题解工作台

汇总区间

给定一个 无重复元素 的 有序 整数数组 nums 。 区间 [a,b] 是从 a 到 b (包含)的所有整数的集合。 返回 恰好覆盖数组中所有数字 的 最小有序 区间范围列表 。也就是说, nums 的每个元素都恰好被某个区间范围所覆盖,并且不存在属于某个区间但不属于 nums 的数字 x 。 列…

category

1

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·driven

bolt

答案摘要

我们可以用双指针 和 找出每个区间的左右端点。 遍历数组,当 $j + 1 < n$ 且 $nums[j + 1] = nums[j] + 1$ 时,指针 向右移动,否则区间 $[i, j]$ 已经找到,将其加入答案,然后将指针 移动到 $j + 1$ 的位置,继续寻找下一个区间。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·driven 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个  无重复元素 的 有序 整数数组 nums

区间 [a,b] 是从 ab(包含)的所有整数的集合。

返回 恰好覆盖数组中所有数字最小有序 区间范围列表 。也就是说,nums 的每个元素都恰好被某个区间范围所覆盖,并且不存在属于某个区间但不属于 nums 的数字 x

列表中的每个区间范围 [a,b] 应该按如下格式输出:

  • "a->b" ,如果 a != b
  • "a" ,如果 a == b

 

示例 1:

输入:nums = [0,1,2,4,5,7]
输出:["0->2","4->5","7"]
解释:区间范围是:
[0,2] --> "0->2"
[4,5] --> "4->5"
[7,7] --> "7"

示例 2:

输入:nums = [0,2,3,4,6,8,9]
输出:["0","2->4","6","8->9"]
解释:区间范围是:
[0,0] --> "0"
[2,4] --> "2->4"
[6,6] --> "6"
[8,9] --> "8->9"

 

提示:

  • 0 <= nums.length <= 20
  • -231 <= nums[i] <= 231 - 1
  • nums 中的所有值都 互不相同
  • nums 按升序排列
lightbulb

解题思路

方法一:双指针

我们可以用双指针 iijj 找出每个区间的左右端点。

遍历数组,当 j+1<nj + 1 < nnums[j+1]=nums[j]+1nums[j + 1] = nums[j] + 1 时,指针 jj 向右移动,否则区间 [i,j][i, j] 已经找到,将其加入答案,然后将指针 ii 移动到 j+1j + 1 的位置,继续寻找下一个区间。

时间复杂度 O(n)O(n),其中 nn 为数组长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
    def summaryRanges(self, nums: List[int]) -> List[str]:
        def f(i: int, j: int) -> str:
            return str(nums[i]) if i == j else f'{nums[i]}->{nums[j]}'

        i = 0
        n = len(nums)
        ans = []
        while i < n:
            j = i
            while j + 1 < n and nums[j + 1] == nums[j] + 1:
                j += 1
            ans.append(f(i, j))
            i = j + 1
        return ans
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Checks the candidate's ability to optimize array traversal.

  • question_mark

    Evaluates how the candidate handles edge cases in a sorted array.

  • question_mark

    Assesses the candidate's approach to time and space complexity trade-offs.

warning

常见陷阱

外企场景
  • error

    Failing to handle single-element ranges correctly.

  • error

    Not optimizing the solution when scaling the array size.

  • error

    Misinterpreting the problem as needing a brute-force solution instead of an efficient array-driven approach.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Allow duplicates in the array and handle them.

  • arrow_right_alt

    Modify the problem to deal with unsorted input arrays.

  • arrow_right_alt

    Implement the problem with additional constraints like a maximum range size.

help

常见问题

外企场景

汇总区间题解:数组·driven | LeetCode #228 简单