LeetCode 题解工作台

学生分数的最小差值

给你一个 下标从 0 开始 的整数数组 nums ,其中 nums[i] 表示第 i 名学生的分数。另给你一个整数 k 。 从数组中选出任意 k 名学生的分数,使这 k 个分数间 最高分 和 最低分 的 差值 达到 最小化 。 返回可能的 最小差值 。 示例 1: 输入: nums = [90], …

category

3

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 滑动窗口(状态滚动更新)

bolt

答案摘要

我们可以将学生的分数按照升序排序,然后使用滑动窗口的方法,每次取大小为 的窗口,计算窗口内的最大值和最小值的差值,最后取所有窗口的差值的最小值。 为什么是取连续的 个学生的分数呢?因为如果不连续,那么最大值和最小值的的差值可能不变,或者变大,但一定不会变小。因此,我们只需要考虑排序后的连续的 个学生的分数。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 滑动窗口(状态滚动更新) 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个 下标从 0 开始 的整数数组 nums ,其中 nums[i] 表示第 i 名学生的分数。另给你一个整数 k

从数组中选出任意 k 名学生的分数,使这 k 个分数间 最高分最低分差值 达到 最小化

返回可能的 最小差值

 

示例 1:

输入:nums = [90], k = 1
输出:0
解释:选出 1 名学生的分数,仅有 1 种方法:
- [90] 最高分和最低分之间的差值是 90 - 90 = 0
可能的最小差值是 0

示例 2:

输入:nums = [9,4,1,7], k = 2
输出:2
解释:选出 2 名学生的分数,有 6 种方法:
- [9,4,1,7] 最高分和最低分之间的差值是 9 - 4 = 5
- [9,4,1,7] 最高分和最低分之间的差值是 9 - 1 = 8
- [9,4,1,7] 最高分和最低分之间的差值是 9 - 7 = 2
- [9,4,1,7] 最高分和最低分之间的差值是 4 - 1 = 3
- [9,4,1,7] 最高分和最低分之间的差值是 7 - 4 = 3
- [9,4,1,7] 最高分和最低分之间的差值是 7 - 1 = 6
可能的最小差值是 2

 

提示:

  • 1 <= k <= nums.length <= 1000
  • 0 <= nums[i] <= 105
lightbulb

解题思路

方法一:排序 + 滑动窗口

我们可以将学生的分数按照升序排序,然后使用滑动窗口的方法,每次取大小为 kk 的窗口,计算窗口内的最大值和最小值的差值,最后取所有窗口的差值的最小值。

为什么是取连续的 kk 个学生的分数呢?因为如果不连续,那么最大值和最小值的的差值可能不变,或者变大,但一定不会变小。因此,我们只需要考虑排序后的连续的 kk 个学生的分数。

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

1
2
3
4
5
class Solution:
    def minimumDifference(self, nums: List[int], k: int) -> int:
        nums.sort()
        return min(nums[i + k - 1] - nums[i] for i in range(len(nums) - k + 1))
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    Candidate demonstrates understanding of sliding window technique and its connection to minimizing the difference in a sorted array.

  • question_mark

    Solution approach emphasizes sorting and sliding window to reduce complexity, rather than brute force or nested loops.

  • question_mark

    Candidate considers edge cases, such as when k is 1, and how the window behaves in different scenarios.

warning

常见陷阱

外企场景
  • error

    Not sorting the array first, which would lead to incorrect results when selecting elements.

  • error

    Misunderstanding the sliding window concept, resulting in inefficient solutions or wrong windows being chosen.

  • error

    Incorrectly handling cases where k is equal to the length of the array, which may require special consideration.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Adjust the problem to find the minimum difference between highest and lowest for a subset of students based on different conditions.

  • arrow_right_alt

    Extend the problem to find the difference for multiple windows or across multiple groups of k students.

  • arrow_right_alt

    Modify the problem to allow for picking non-consecutive scores to minimize the difference.

help

常见问题

外企场景

学生分数的最小差值题解:滑动窗口(状态滚动更新) | LeetCode #1984 简单