学校在拍年度纪念照时,一般要求学生按照 非递减 的高度顺序排列。
请你返回能让所有学生以 非递减 高度排列的最小必要移动人数。
注意,当一组学生被选中时,他们之间可以以任何可能的方式重新排序,而未被选中的学生应该保持不动。
示例:输入:heights = [1,1,4,2,1,3]
输出:3
解释: 当前数组:[1,1,4,2,1,3]
目标数组:[1,1,1,2,3,4]
在下标 2 处(从 0 开始计数)出现 4 vs 1 ,所以我们必须移动这名学生。
在下标 4 处(从 0 开始计数)出现 1 vs 3 ,所以我们必须移动这名学生。
在下标 5 处(从 0 开始计数)出现 3 vs 4,所以我们必须移动这名学生。示例 2:
输入:heights = [5,1,2,3,4]
输出:5示例 3:
输入:heights = [1,2,3,4,5]
输出:0提示:
1 <= heights.length <= 100 1 <= heights[i] <= 100
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/height-checker
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
用C++:
在LeetCode上提交的代码:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int heightChecker(vector<int>& heights) {
vector<int> hei(heights);
sort(hei.begin(), hei.end()); //sort对于vector向量的排序,升序排列
int len = heights.size();
int coun = 0;
vector<int>::size_type i;
for (i = 0; i < len; i++)
{
if (heights[i] != hei[i])
{
coun++;
}
}
return coun;
}
int main()
{
int num;
vector<int> heights;
while (cin >> num)
{
heights.push_back(num);
if (cin.get() == '\n')
{
break;
}
}
int c;
c = heightChecker(heights);
cout << c << endl;
return 0;
}
};
在自己的编译器上写的:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int heightChecker(vector<int>& heights)
{
vector<int> hei(heights);
sort(hei.begin(), hei.end()); //sort对于vector向量的排序,升序排列
int len = heights.size();
int coun = 0;
vector<int>::size_type i;
for (i = 0; i < len; i++)
{
if (heights[i] != hei[i])
{
coun++;
}
}
return coun;
}
int main()
{
int num;
vector<int> heights;
while (cin >> num)
{
heights.push_back(num);
if (cin.get() == '\n')
{
break;
}
}
int c;
c = heightChecker(heights);
cout << c << endl;
return 0;
}
思路:
从键盘获取输入的数组→把该数组传入函数→用vector的sort函数排序(该函数是升序排列)→用排序后的和原本的数组一一按顺序对比,记录相应位置的数字不一样的个数,这个数就是要输出的