Leetcode 1984. Minimum Difference Between Highest and Lowest of K Scores

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Minimum Difference Between Highest and Lowest of K Scores

2. Solution

解析:Version 1,先对数组排序,K个数的最小差值一定出现在相邻的K个数中,每K个有序数,其最大的差值为两边的数字,依次遍历计算相邻K个数的差值,取最小值即可。

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

Reference

  1. https://leetcode.com/problems/minimum-difference-between-highest-and-lowest-of-k-scores/
如果有收获,可以请我喝杯咖啡!