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;
}
};