// C++
/* 学校在拍年度纪念照时,一般要求学生按照 非递减 的高度顺序排列。
请你返回至少有多少个学生没有站在正确位置数量。该人数指的是:能让所有学生以 非递减 高度排列的必要移动人数。
示例
输入:[1,1,4,2,1,3]
输出:3
解释:
高度为 4、3 和最后一个 1 的学生,没有站在正确的位置。
*/
// 解题思路:先复制,后排序,再对比,不同加1.可在排序上优化空间和时间。
class Solution {
public:
int heightChecker(vector<int>& heights) {
int count = 0;
const int len = heights.size();
// 拷贝heights
vector<int> my_height = heights;
// 利用选择排序对my_height进行排序
for (int i = 0; i < len - 1; i++)
{
int minIndex = i;
for (int j = i+1; j < len; j++)
{
if (my_height[j] < my_height[minIndex])
{
minIndex = j;
}
}
int temp = my_height[i];
my_height[i] = my_height[minIndex];
my_height[minIndex] = temp;
}
// 对比排序前和排序后不同元素的数量
for (int i = 0; i < len; i++)
{
if (my_height[i] != heights[i])
++count;
}
return count;
}
};
经典的排序算法:
排序算法

探讨了学生按高度非递减排列的问题,通过C++代码实现了一个解决方案,包括复制数组、选择排序和对比计数的过程,旨在找出未站在正确位置的学生数量。
892

被折叠的 条评论
为什么被折叠?



