L1-027 出租
题解
朴素做法就不说了,用数组简单模拟一下就可以了,时间复杂度为$O(n^2)$。
另一种做法就是 map + set 的方式,set 主要是去重并按从大到小排序,十分符合 arr 数组要求,而 map 主要记录手机号码在 arr 中的下标,这样在遍历手机号码是可以直接映射到arr下标,时间复杂度估计为$O(n)$。
#include <iostream> #include <set> #include <map> using namespace std; string s; // 内部从大到小排序 set <int, greater<int> > st; // set、map 时间复杂度可以有效降至O(n) int main() { cin >> s; for (int i = 0; i < s.size(); ++i) { st.insert(s[i] - '0'); } int temp = 0; map <int, int> mp; set <int> :: iterator it = st.begin(); cout << "int[] arr = new int[]{"; while (it != st.end()) { cout << *it; mp[*it] = temp; ++temp; if (temp == st.size()) { cout << "};" << endl; } else { cout << ","; } ++it; } // 直接采用映射关系 cout << "int[] index = new int[]{"; for (int i = 0; i < s.size(); ++i) { if (!i) { cout << mp[s[i] - '0']; } else { cout << "," << mp[s[i] - '0']; } } cout << "};" << endl; return 0; }