这里是华为2015年8月份的题目:整数排序
对输入的数字串按升序排序,对于连续数字,只保留最小数字和最大数字。
输入:一串数字:例如4,7,25,36,8,9,49,37,38
输出:4,7,9,25,36,38,49
程序中相关函数介绍:
string 类型
vector 容器
string:
int find(char c, int pos = 0)/从pos开始查找字符c在当前字符串的位置/
const char c_str()const; /返回一个以null终止的c字符串*/
string substr(int pos = 0, int n = npos) const; /返回pos开始的n个字符组成的字符串/
string &insert(int p0, const string &s, int pos, int n); /在p0处插入s字符串,从pos开始的n个字符/
string &erase(int pos = 0, int n = npos); /删除pos开始的n个字符,返回修改后的字符/
vector:
vector vec;
vec.push_back(a)/在尾部插入元素/
vec.insert(vec.begin() + i, a)/在第i+1个元素前面插入a/
vec.erase(vec.begin() + 2) /删除第3个元素/
vec.size();
vec.clear();
/算法/
reverse(vec.begin(), vec.end()) /将元素翻转/
sort(vec.begin(), vec.end()) /默认是按升序排列,即从小到大/
other_api:
atoi /函数的功能是将字符串转换为整数/
程序已经在vs2005得到了验证
#include
#include
#include
#include
using namespace std;
void swap(int &a, int &b);
int partition(vector<int> &arr, int low, int high);
void quick_sort(vector<int> &arr, int low, int high);
void deleteMid(vector<int> &arr);
int main(int argc, char *argv[])
{
vector<int> arr;
string str_nums;
while(cin >> str_nums)
{
int comma1 = 0;
int comma2 = 0;
comma1 = str_nums.find(',', 0);
arr.push_back(atoi(str_nums.substr(0,comma1).c_str()));
while(comma1 < str_nums.size())
{
comma2 = str_nums.find(',', comma1 + 1);
if (comma2 == -1)
{
arr.push_back(atoi(str_nums.substr(comma1 + 1, str_nums.size() - comma1 - 1).c_str()));
break;
}
arr.push_back(atoi(str_nums.substr(comma1 + 1, comma2 - comma1 - 1).c_str()));
comma1 = comma2;
}
quick_sort(arr, 0, arr.size() - 1);
deleteMid(arr);
}
Sleep(3000);
return 0;
}
void swap(int &a, int &b)
{
int tmp;
tmp = a;
a = b;
b = tmp;
return;
}
int partition(vector<int> &arr, int low, int high)
{
int pivotkey;
pivotkey = arr[low];
while (low < high)
{
/*这里采用了两端扫描排序*/
while (low < high && arr[high] >= pivotkey)
{
high--;
}
swap(arr[low], arr[high]);
while (low < high && arr[low] <= pivotkey)
{
low++;
}
swap(arr[low], arr[high]);
}
return low;
}
void quick_sort(vector<int> &arr, int low, int high)
{
if (low < high)/*这里不要忘记判断,第一次编写的时候,忘记添加,结果很惨啊!*/
{
int pivot = partition(arr, low, high);
quick_sort(arr, low, pivot-1);
quick_sort(arr, pivot+1, high);
}
return;
}
void deleteMid(vector<int> &arr)/*这个函数还是很有含量的,可以仔细看看*/
{
vector<int> result;
int start = 0;
int end = 0;
for (int i = 0; i < arr.size() - 1; i ++)
{
if (arr[i + 1] != arr[i] + 1)
{
result.push_back(arr[i]);
if (i == arr.size()-2)
{
result.push_back(arr[i + 1]);
}
}
else
{
start = i;
int j = 0;
for ( j = i; j < arr.size() - 1; j ++)
{
if (arr[j + 1] != arr[j] + 1)
{
break;
}
}
end = j;
result.push_back(arr[start]);
result.push_back(arr[end]);
/*这里如果end是倒数第二个数,那么最后一个也就要插入容器中*/
if (end == arr.size() - 2)
{
result.push_back(arr[end + 1]);
}
i = end; /*这里要更新i的值,很重要!*/
}
}
for (int i = 0; i < result.size(); i ++)
{
cout << result[i] << " ";
}
return;
}