返回信息流给定一个数组,然后按数组中数字出现的频率,由高到低排序,相同频率的按原数组顺序排序。
输入:
1,2,3,4,2
输出:
2,2,1,3,4
输入:
3,2,3,2
输出:
3,3,2,2
这是一条镜像帖。来源:北邮人论坛 / acm-icpc / #90943同步于 2016/9/2
该镜像源已超过 30 天没有更新,可能在源站已被删除。
ACM_ICPC机器人发帖
新手求教一道排序算法题
Argue
2016/9/2镜像同步19 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
这题简单,看我一行搞定
reduce(lambda x, y: x + y, map(lambda (x, y): [x] * y, sorted(Counter([1, 2, 3, 4, 2]).items(), key=lambda x: x[1], reverse=True)), [])
【 在 aquamarine 的大作中提到: 】
: 这题简单,看我一行搞定
: reduce(lambda x, y: x + y, map(lambda (x, y): [x] * y, sorted(Counter([1, 2, 3, 4, 2]).items(), key=lambda x: x[1], reverse=True)), [])
能讲下思路么,只会用c++,有点看不懂。谢谢
```C\C++
// 二次排序
bool sortFunc(vector<int> p1, vector<int> p2) {
if (p1[1] > p2[1])
return true;
else if (p1[1] == p2[1] && p1[2] < p2[2])
return true;
return false;
}
vector<int> mySort(vector<int> &a) {
if (a.size() <= 2)
return a;
vector<int> res;
map<int, int> m1;
map<int, int> m2;
for (int i = 0; i < a.size(); i++) {
if (m2.find(a[i]) == m2.end())
m2[a[i]] = i;
m1[a[i]] += 1;
}
vector<vector<int> > v;
for (map<int, int>::iterator it = m1.begin(); it != m1.end(); ++it) {
vector<int> num(3,0);
num[0] = it->first; // 数组中的值
num[1] = it->second; // 值出现的次数
num[2] = m2[it->first]; // 值在数组中的index
v.push_back(num);
}
sort(v.begin(), v.end(), sortFunc);
for (int i = 0; i < v.size(); i++) {
int j = v[i][1];
while(j--)
res.push_back(v[i][0]);
}
return res;
}
```
【 在 Argue 的大作中提到: 】
: 给定一个数组,然后按数组中数字出现的频率,由高到低排序,相同频率的按原数组顺序排序。
: 输入:
: 1,2,3,4,2
: ...................
【 在 tastier 的大作中提到: 】
: [md]
: ```C\C++
: // 二次排序
: ...................
是将次数计算出来后,再把次数排序么?
echo "1 2 3 4 2" | tr -s ' ' '\n' | sort -n | uniq -c | sort -nrs -k1 | ruby -e 'STDIN.each{|l| a,b=l.split; print (b+" ")*a.to_i};puts'
输出:
2 2 1 3 4
嗯,先对次数排序,然后对index排序,没想到更好的方法,等其他童鞋的好方法吧
【 在 Argue 的大作中提到: 】
:
: 是将次数计算出来后,再把次数排序么?
装完逼也给人家解释下呗
[ema2]
【 在 aquamarine 的大作中提到: 】
: 这题简单,看我一行搞定
: reduce(lambda x, y: x + y, map(lambda (x, y): [x] * y, sorted(Counter([1, 2, 3, 4, 2]).items(), key=lambda x: x[1], reverse=True)), [])
【 在 aquamarine 的大作中提到: 】
: 这题简单,看我一行搞定
: reduce(lambda x, y: x + y, map(lambda (x, y): [x] * y, sorted(Counter([1, 2, 3, 4, 2]).items(), key=lambda x: x[1], reverse=True)), [])
对不起 你的代码目前一行搞不定 少了这句
```python
from collections import Counter
```