lintcode练习-143. 排颜色 II

描述

给定一个有n个对象(包括k种不同的颜色,并按照1到k进行编号)的数组,将对象进行分类使相同颜色的对象相邻,并按照1,2,...k的顺序进行排序。

You are not suppose to use the library's sort function for this problem.

k <= n

您在真实的面试中是否遇到过这个题?  是

样例

给出colors=[3, 2, 2, 1, 4]k=4, 你的代码应该在原地操作使得数组变成[1, 2, 2, 3, 4]

挑战

一个相当直接的解决方案是使用计数排序扫描2遍的算法。这样你会花费O(k)的额外空间。你否能在不使用额外空间的情况下完成?

from collections import Counter


class Solution:
    """
    @param colors: A list of integer
    @param k: An integer
    @return: nothing
    """

    def sortColors2(self, colors, k):
        # write your code here
        c = Counter(colors)
        l = 0
        for i in range(1, k+1):
            for v in range(c[i]):
                colors[l] = i
                l += 1

猜你喜欢

转载自blog.csdn.net/qq_36387683/article/details/81477963