- 比起for循环string再内层for循环vector找到数字并得到下标
vector排序完成后,遍历一遍用一个数组来存每个数的下标,之后在循环一次string直接根据值去数组索引高效得多
用空间换时间
#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string tel;
cin >> tel;
int num[10] = { 0 };
vector<int> exnum;
for (int i = 0; i < tel.size(); ++i) {
if (!num[tel[i] - '0']) {
num[tel[i] - '0'] = 1;
exnum.push_back(tel[i]-'0');
}
}
sort(exnum.rbegin(), exnum.rend());
cout << "int[] arr = new int[]{";
for (int i = 0; i < exnum.size(); ++i) {
num[exnum[i]] = i;
if (i)
cout << ",";
cout << exnum[i];
}
cout << "};"<<endl;
cout << "int[] index = new int[]{";
for (int i = 0; i < tel.size(); ++i) {
if (i)
cout << ",";
cout << num[tel[i] - '0'];
}
cout << "};";
system("pause");
return 0;
}
网友评论