1051. Height Checker。

Students are asked to stand in non-decreasing order of heights for an annual photo.

Return the minimum number of students not standing in the right positions. (This is the number of students that must move in order for all students to be standing in non-decreasing order of height.)

原文链接:https://leetcode.com/problems/height-checker/


要求一组学生按照身高以非递减的方式进行排队,也就是一个数组应该是非递减的排列方式,但是此时数组中有些元素没有按照这种规则进行排序,需要我们找出这些不在对应位置上的元素有多少个。


把元数组进行排序,然后与未排序的数组进行对比,找出对应位置上元素不一样的个数即可。

class Solution {
public:
    int heightChecker(vector<int>& heights) {
        int count = 0;
        vector<int> sorted = heights; // 排序
        sort(sorted.begin(),sorted.end());
        for(int i=0;i<sorted.size();i++) {
            if(sorted[i] != heights[i]) // 对应位置不相等,则说明站错了队
                count++;
        }
        return count;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值