0

我希望这个整数数组根据它的出现次数以正确的顺序排序。

question = [[1, 7, 8, 9, 10, 11, 12, 19, 20, 21, 31, 32, 34, 35, 36, 37, 38, 39, 40, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 81, 129, 132, 133, 134, 135, 136, 139], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 19, 20, 21, 22, 23, 24, 25, 26, 27, 29, 31, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 81, 129, 130, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141], [30], [77]] 

question.flatten.uniq.size = 90

answer = sort_it(question)

answer = [77, 68, 8, 9, 10, 11, 12, 19, 20, 21, 31, 139, 34, 35, 36, 37, 38, 39, 40, 42, 43, 44, 135, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 136, 66, 67, 7, 70, 71, 72, 73, 74, 75, 76, 1, 78, 79, 81, 129, 132, 133, 134, 45, 65, 32, 2, 3, 4, 5, 6, 13, 14, 15, 16, 17, 22, 23, 24, 25, 26, 27, 29, 33, 41, 69, 130, 137, 138, 140, 141, 30]

answer.uniq.size = 90

这是我的 Ruby 代码:

def sort_it(actual)
        join=[]
        buffer = actual.dup 
        final = [ ]

                (actual.size-2).downto(0) {|j|
                join.unshift(actual.map{|i| i }.inject(:"&"))
                actual.pop
                }
        ordered_join =  join.reverse.flatten
        final << ordered_join
        final << buffer.flatten - ordered_join

        final.flatten
end

这种方法可以吗?有没有更有效的方法?

编辑:

作为对 tokland 和 niklas 的致敬,编辑了之前顺序错误的答案。谢谢!

4

2 回答 2

4

使用group_by

question.flatten.group_by{|x| x}.sort_by{|k, v| -v.size}.map(&:first)
于 2012-05-01T12:49:03.570 回答
0

用 sort_by{|k, v| 回答 -v.size} 每次比较元素时调用 v.size。更有效的解决方案:

question.flatten.group_by(&:to_i).map{|k,v| [k, -v.size]}.sort_by(&:last).map(&:first)

虽然数组的大小很容易获得,但它是不必要的开销(O(排序算法)而不是 O(n)),而且这个习惯用法对于更昂贵的操作无论如何都很好记住

于 2012-05-01T18:36:53.350 回答