1984. Minimum Difference Between Highest and Lowest of K Scores - Easy

前往題目

想法

  • 雙指針

思路

  1. 排序後,左右鄰居都是最靠近自己的
  2. 根據k定義sliding window雙指針
  3. 疊代整個陣列找出最小值

Code

class Solution {
    public int minimumDifference(int[] nums, int k) {

        Arrays.sort(nums);
        
        int res = Integer.MAX_VALUE;

        int left = 0, right = k - 1; // Sliding window雙指針

        // 疊代整個陣列
        while (right < nums.length) {
            res = Math.min(res, nums[right] - nums[left]);
            ++left;
            ++right;
        }

        return res;
    }
}

1984. Minimum Difference Between Highest and Lowest of K Scores - Easy
https://f88083.github.io/2024/07/09/1984-Minimum-Difference-Between-Highest-and-Lowest-of-K-Scores/
作者
Simon Lai
發布於
2024年7月9日
許可協議