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;