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;
}
标签:lowest,1984,highest,int,score,easy,between,difference,leetcode
From: https://www.cnblogs.com/iyiluo/p/16858849.html