当前位置:网站首页>Leetcode1984. Minimum difference in student scores

Leetcode1984. Minimum difference in student scores

2022-07-07 22:39:00 Small size big ha

subject :

To give you one Subscript from 0 Start Array of integers for nums , among nums[i] It means the first one i A student's grade . I'll give you another integer k .

Select any... From the array k A student's grade , Make this k Between scores The highest and Lowest score Of Difference value achieve To minimize the .

Return possible Minimum difference .

Investigation contents : Sort + The sliding window

The main idea of the topic : Take whatever in the array k It's worth , And then let this k The difference between the maximum value and the minimum value is the smallest .

Ideas : Sort the array first , Think after sorting a[0] To a[k-1] this k It's worth , Suppose we put a[k-1] Replace with array subscript k-1 The number behind ( A number larger than him ), Then the maximum value is determined by a[k-1] Become a larger number , And the minimum value does not change , Then the difference between the maximum value and the minimum value will become larger . So we use this method , from a[0]-a[0+k-1] To a[i]-a[ i+k-1=nums.size() ], Each calculation difference , Record the smallest one as ans.

The attached code :

class Solution {
public:
    int minimumDifference(vector<int>& nums, int k) {
        int n=nums.size();
        sort(nums.begin(),nums.end());
        int ans=INT_MAX;
        for(int i=0;i+k-1<n;i++)
        {
            ans=min(ans,nums[i+k-1]-nums[i]);
        }
        return ans;
    }
};

原网站

版权声明
本文为[Small size big ha]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130603561613.html