Rust 力扣 - 1984. 学生分数的最小差值

文章目录

题目描述

题解思路

原数组 nums 排序,遍历nums中下标为[0, nums.len() - k]的学生分数

假设当前遍历的下标为i则,以 i 下标为最小值的学生分数的最小差值为nums[i + k - 1] - nums[i]

取最小差值的最小值即为本题结果

题解代码

rust 复制代码
impl Solution {
    pub fn minimum_difference(mut nums: Vec<i32>, k: i32) -> i32 {
        nums.sort();

        let mut ans = i32::MAX;

        for i in 0..=nums.len() - k as usize {
            ans = ans.min(nums[i + k as usize - 1] - nums[i]);
        }

        if ans == i32::MAX { 0 } else { ans }
    }
}

题目链接

https://leetcode.cn/problems/minimum-difference-between-highest-and-lowest-of-k-scores/

相关推荐
parafeeee7 小时前
程序人生-Hello’s P2P
数据库·后端·asp.net
weixin_458872617 小时前
东华复试OJ二刷复盘2
算法
Charlie_lll7 小时前
力扣解题-637. 二叉树的层平均值
算法·leetcode
MediaTea7 小时前
Python:collections.Counter 常用函数及应用
开发语言·python
爱淋雨的男人7 小时前
自动驾驶感知相关算法
人工智能·算法·自动驾驶
wen__xvn8 小时前
模拟题刷题3
java·数据结构·算法
bug攻城狮8 小时前
Spring Boot应用内存占用分析与优化
java·jvm·spring boot·后端
LawrenceLan8 小时前
37.Flutter 零基础入门(三十七):SnackBar 与提示信息 —— 页面反馈与用户交互必学
开发语言·前端·flutter·dart