leetcode-1984-easy

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

思路一:先排序,然后对比 k 间距的两数之间的值。刚开始想歪了,用 k 个不同的起点遍历,每次自增的跨度是 k,虽然通过了,但是用了双层循环,代码看起来比较丑。看了题解,发现一次遍历就行,把 k 的间距当成滑动窗口,在数组上遍历,最小值就是所求解。

    public int minimumDifference(int[] nums, int k) {
        Arrays.sort(nums);

        int min = Integer.MAX_VALUE;
        for (int i = 0; i < k; i++) {
            for (int j = i; j <= nums.length - k; j+=k) {
                min = Math.min(nums[j + k - 1] - nums[j], min);
            }
        }

        return min;
    }
public int minimumDifference(int[] nums, int k) {
    Arrays.sort(nums);

    int min = Integer.MAX_VALUE;
    for (int j = 0; j <= nums.length - k; j++) {
        min = Math.min(nums[j + k - 1] - nums[j], min);
    }

    return min;
}
posted @   iyiluo  阅读(14)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示