[LeetCode] 1984. Minimum Difference Between Highest and Lowest of K Scores

You are given a 0-indexed integer array nums, where nums[i] represents the score of the ith student. You are also given an integer k.

Pick the scores of any k students from the array so that the difference between the highest and the lowest of the k scores is minimized.

Return the minimum possible difference.

Example 1:

Input: nums = [90], k = 1
Output: 0
Explanation: There is one way to pick score(s) of one student:
- [90]. The difference between the highest and lowest score is 90 - 90 = 0.
The minimum possible difference is 0.

Example 2:

Input: nums = [9,4,1,7], k = 2
Output: 2
Explanation: There are six ways to pick score(s) of two students:
- [9,4,1,7]. The difference between the highest and lowest score is 9 - 4 = 5.
- [9,4,1,7]. The difference between the highest and lowest score is 9 - 1 = 8.
- [9,4,1,7]. The difference between the highest and lowest score is 9 - 7 = 2.
- [9,4,1,7]. The difference between the highest and lowest score is 4 - 1 = 3.
- [9,4,1,7]. The difference between the highest and lowest score is 7 - 4 = 3.
- [9,4,1,7]. The difference between the highest and lowest score is 7 - 1 = 6.
The minimum possible difference is 2.

Constraints:

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

学生分数的最小差值。

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

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

返回可能的 最小差值 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-difference-between-highest-and-lowest-of-k-scores
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这道题的思路是排序 + 滑动窗口。这里有一个 corner case 需要排除,就是当 k = 1 的时候,因为最大值和最小值是同一个数字,所以结果是 0。对于一般的情况,因为排完序之后,左指针指向的是最小的元素,右指针指向的是最大的元素,所以只要卡好左右指针的距离一直等于 k,我们就可以扫描一遍数组从而得到所有 k 个数字中间那个最小的差值。

时间O(nlogn)

空间O(1)

Java实现

 1 class Solution {
 2     public int minimumDifference(int[] nums, int k) {
 3         // corner case
 4         if (k == 1) {
 5             return 0;
 6         }
 7         
 8         // normal case
 9         Arrays.sort(nums);
10         int res = Integer.MAX_VALUE;
11         for (int i = k - 1; i < nums.length; i++) {
12             res = Math.min(res, nums[i] - nums[i - k + 1]);
13         }
14         return res;
15     }
16 }

 

LeetCode 题目总结

posted @ 2021-08-30 23:55  CNoodle  阅读(223)  评论(0编辑  收藏  举报