自定义排序阵列



大小n的整数,ARR的数组定义为{a,a,。。。, A }。它必须将ARR作为参数,按上升频率顺序排序其元素,然后将分类数组的每个元素打印为新的输出行。如果两个或多个元素具有相同的频率,则该子集的元素应以非折叠顺序排序。

Sample Input 0 53124 
Sample Output 0 1342 

我试图在Java和Python中解决这个问题,并在Java中工作,但不确定我该如何处理Python。

public class CustomSort {
    public static void main(String[] args) {
        int[] arr = { 5, 3, 1, 2, 2, 2, 2, 2, 2, 2, 6, 6, 6, 6, 6, 5, 4 };
        customSort(arr);
    }
    static void customSort(int[] arr) {
        Map<Integer, Integer> map = new HashMap<>();
        List<Integer> numbers = new ArrayList<>();
        for (int i : arr) {
            if(map.containsKey(i)) {
                map.put(i, map.get(i) + 1);
            } else {
                map.put(i, 1);
            }

            if (!numbers.contains(i)) {
                numbers.add(i);
            }
        }
        Collections.sort(numbers);
        List<Integer> returning = new ArrayList<>(numbers);
        int count = 1;
        while(!returning.isEmpty()) {
            returning = print(returning, map, count);
            count++;
        }
    }
    static List<Integer> print(List<Integer> numbers, Map<Integer, Integer> map, int howManyItens) {
        List<Integer> returning = new ArrayList<>();
        for (Integer integer : numbers) {
            if(map.get(integer) == howManyItens) {
                for (int i = 1; i <= howManyItens; i++) {
                    System.out.println(integer);
                }
            } else {
                returning.add(integer);
            }
        }
        return returning;
    }
}

我应该如何在python中执行此操作?

def customSort(arr):
    # what should I do here?

您可以做类似:

的事情
>>> li=[ 5, 3, 1, 2, 2, 2, 2, 2, 2, 2, 6, 6, 6, 6, 6, 5, 4 ]
>>> sorted(li, key=lambda i: li.count(i))
[3, 1, 4, 5, 5, 6, 6, 6, 6, 6, 2, 2, 2, 2, 2, 2, 2]

或者,您可以做:

def c_sort(li):
    cnt={i:li.count(i) for i in set(li)}
    return sorted(li, key=lambda e: cnt[e])
>>> c_sort(li)
[3, 1, 4, 5, 5, 6, 6, 6, 6, 6, 2, 2, 2, 2, 2, 2, 2]

如果您想要每个元素值的次要键,请形成一个元组:

def c_sort(li):
    cnt={i:li.count(i) for i in set(li)}
    return sorted(li, key=lambda e: (cnt[e], e))
>>> c_sort(li)
[1, 3, 4, 5, 5, 6, 6, 6, 6, 6, 2, 2, 2, 2, 2, 2, 2]

最新更新