LeetCode 题解工作台

找出分区值

给你一个 正 整数数组 nums 。 将 nums 分成两个数组: nums1 和 nums2 ,并满足下述条件: 数组 nums 中的每个元素都属于数组 nums1 或数组 nums2 。 两个数组都 非空 。 分区值 最小 。 分区值的计算方法是 |max(nums1) - min(nums2)…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·排序

bolt

答案摘要

题目要求分区值最小,那么我们可以将数组排序,然后取相邻两个数的差值的最小值即可。 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 是数组的长度。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个 整数数组 nums

nums 分成两个数组:nums1nums2 ,并满足下述条件:

  • 数组 nums 中的每个元素都属于数组 nums1 或数组 nums2
  • 两个数组都 非空
  • 分区值 最小

分区值的计算方法是 |max(nums1) - min(nums2)|

其中,max(nums1) 表示数组 nums1 中的最大元素,min(nums2) 表示数组 nums2 中的最小元素。

返回表示分区值的整数。

 

示例 1:

输入:nums = [1,3,2,4]
输出:1
解释:可以将数组 nums 分成 nums1 = [1,2] 和 nums2 = [3,4] 。
- 数组 nums1 的最大值等于 2 。
- 数组 nums2 的最小值等于 3 。
分区值等于 |2 - 3| = 1 。
可以证明 1 是所有分区方案的最小值。

示例 2:

输入:nums = [100,1,10]
输出:9
解释:可以将数组 nums 分成 nums1 = [10] 和 nums2 = [100,1] 。 
- 数组 nums1 的最大值等于 10 。 
- 数组 nums2 的最小值等于 1 。 
分区值等于 |10 - 1| = 9 。 
可以证明 9 是所有分区方案的最小值。

 

提示:

  • 2 <= nums.length <= 105
  • 1 <= nums[i] <= 109
lightbulb

解题思路

方法一:排序

题目要求分区值最小,那么我们可以将数组排序,然后取相邻两个数的差值的最小值即可。

时间复杂度 O(n×logn)O(n \times \log n),空间复杂度 O(logn)O(\log n)。其中 nn 是数组的长度。

1
2
3
4
5
class Solution:
    def findValueOfPartition(self, nums: List[int]) -> int:
        nums.sort()
        return min(b - a for a, b in pairwise(nums))
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    Ask if sorting simplifies the partition calculation.

  • question_mark

    Check understanding of Array plus Sorting pattern.

  • question_mark

    Probe knowledge of minimizing difference between subarray extremes.

warning

常见陷阱

外企场景
  • error

    Not sorting before checking partitions leads to incorrect minimum values.

  • error

    Attempting all subset splits results in time limit exceeded for large arrays.

  • error

    Forgetting that the array must be split into two non-empty subarrays.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Find the partition value in a descending array without sorting first.

  • arrow_right_alt

    Compute maximum partition value instead of minimum.

  • arrow_right_alt

    Handle arrays with duplicate elements while minimizing partition value.

help

常见问题

外企场景

找出分区值题解:数组·排序 | LeetCode #2740 中等