LeetCode题—数组tag:1051. 高度检查器

学校在拍年度纪念照时,一般要求学生按照 非递减 的高度顺序排列。

请你返回能让所有学生以 非递减 高度排列的最小必要移动人数。

注意,当一组学生被选中时,他们之间可以以任何可能的方式重新排序,而未被选中的学生应该保持不动。
示例:

输入: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函数排序(该函数是升序排列)→用排序后的和原本的数组一一按顺序对比,记录相应位置的数字不一样的个数,这个数就是要输出的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值