数据结构复习零散集合

本文详细解析了插入排序算法的实现,通过一个具体的百度校招题目——寻找第三便宜的帽子,展示了排序算法的实际应用。此外,还介绍了两种常见的字符串输入方法,包括使用字符数组和动态分配内存的方式。

1.插入排序的实现(百度校招PHP2017第一题,找出第三便宜的帽子)

#include<iostream>
using namespace std;
int main()
{
	int N;
	cin >> N;
	int *hatPrices = new int[N + 1];
	for (int i = 1; i <= N; i++)
		cin >> *(hatPrices + i);
	for (int i = 2; i <= N; i++)
	{
		if (*(hatPrices + i) < *(hatPrices + i - 1))
		{
			*hatPrices = *(hatPrices + i);
			int j = 0;
			for (j = i - 1; *hatPrices < *(hatPrices + j); j--)
			{
				*(hatPrices + j + 1) = *(hatPrices + j);
			}
			*(hatPrices + j + 1) = *hatPrices;
		}
	}
	int count = 0;
	for (int i = 1; i <N; i++)
	{
		if (*(hatPrices + i) < *(hatPrices + i + 1))
			count++;
		if (count == 2)
			cout << *(hatPrices + i + 1);
		break; //这个很重要
	}
	if (count<2)
		cout << -1;
	delete[] hatPrices;
	return 0;
}

2.如何输入一个字符串

方法一:

//定义一个字符数组

char s[100];
cin>>s; //gets(s)

方法二:

//申请堆区(也是定义一个字符串)

char *s=new char[N];
cin>>s; //get(s)
...
delete s;

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值