1984. Minimum Difference Between Highest and Lowest of K Scores

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

思路:

排序一下就行

代码:

func minimumDifference(nums []int, k int) int {
    n := len(nums)
    if len(nums) == 1{
        return 0
    }
    sort.Ints(nums)
    minNum := 999999
    for i:=0;i<n-k+1;i++{
        minNum = min(minNum, nums[i+k-1]-nums[i])
    }
    return minNum
}

func min(a, b int)int{
    if a>b{
        return b 
    }else{
        return a
    }

}

代码效率:

执行用时:12 ms, 在所有 Go 提交中击败了94.74%的用户
内存消耗:5 MB, 在所有 Go 提交中击败了89.47%的用户


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!