题解 | 无法吃午餐的学生数量

无法吃午餐的学生数量

https://www.nowcoder.com/practice/2dac3d7567f741a88ec551caf907934d


int countStudents(int* students, int studentslen, int* sandwiches, int sandwicheslen) {
    // 统计学生中偏好0和1的数量(无需模拟队列,更高效且无内存风险)
    int cnt0 = 0, cnt1 = 0;
    for (int i = 0; i < studentslen; i++) {
        if (students[i] == 0) cnt0++;
        else cnt1++;
    }

    // 遍历三明治,依次消耗对应偏好的学生
    for (int i = 0; i < sandwicheslen; i++) {
        if (sandwiches[i] == 0) {
            if (cnt0 > 0) cnt0--;
            else break; // 没有偏好0的学生,后续三明治无法分配
        } else {
            if (cnt1 > 0) cnt1--;
            else break; // 没有偏好1的学生,后续三明治无法分配
        }
    }

    // 剩余学生数即为无法拿到三明治的人数
    return cnt0 + cnt1;
}
  

全部评论

相关推荐

程序员小白条:要写技术栈上去,项目这东西再写的怎么牛,没具象化的竞赛,奖项,开源做支撑,在面试官看来一眼假
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务