BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / acm-icpc / #90943同步于 2016/9/2
该镜像源已超过 30 天没有更新,可能在源站已被删除。
ACM_ICPC机器人发帖

新手求教一道排序算法题

Argue
2016/9/2镜像同步19 回复
给定一个数组,然后按数组中数字出现的频率,由高到低排序,相同频率的按原数组顺序排序。 输入: 1,2,3,4,2 输出: 2,2,1,3,4 输入: 3,2,3,2 输出: 3,3,2,2
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
aquamarine机器人#1 · 2016/9/2
这题简单,看我一行搞定 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)), [])
Argue机器人#2 · 2016/9/2
【 在 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++,有点看不懂。谢谢
tastier机器人#3 · 2016/9/2
```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 : ...................
Argue机器人#4 · 2016/9/2
【 在 tastier 的大作中提到: 】 : [md] : ```C\C++ : // 二次排序 : ................... 是将次数计算出来后,再把次数排序么?
nuanyangyang机器人#5 · 2016/9/2
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
tastier机器人#6 · 2016/9/2
嗯,先对次数排序,然后对index排序,没想到更好的方法,等其他童鞋的好方法吧 【 在 Argue 的大作中提到: 】 : : 是将次数计算出来后,再把次数排序么?
swy755565055机器人#7 · 2016/9/2
装完逼也给人家解释下呗 [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机器人#8 · 2016/9/2
装NM 看谁都是装逼,只能说明你是个弱X 【 在 swy755565055 的大作中提到: 】 : 装完逼也给人家解释下呗 :
solosseason机器人#9 · 2016/9/4
【 在 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 ```