143.Sort Colors II-排颜色 II(中等题)

来源:互联网 发布:安德罗妮淘宝 编辑:程序博客网 时间:2024/05/22 15:17

排颜色 II

  1. 题目

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

    注意事项
    不能使用代码库中的排序函数来解决这个问题

  2. 样例

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

  3. 挑战

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

  4. 题解

    由于要求不适用额外空间,我们这里用colors数组来存每种颜色出现的次数,colors[k - 1]表示颜色k出现的次数(用负数表示以示区分)。首先遍历一遍计算出每种颜色出现的次数,再从尾部开始填充颜色。

class Solution {    /**     * @param colors: A list of integer     * @param k: An integer     * @return: nothing     */    public void sortColors2(int[] colors, int k) {        for (int i=0;i<colors.length;)        {            if (colors[i] <= 0)            {                i++;                continue;            }            else if (colors[colors[i]-1] >= 0)            {                int tmp = colors[i]-1;                swap(colors, i, colors[i] - 1);                  colors[tmp] = -1;              }            else            {                colors[colors[i]-1]--;                colors[i] = 0;                i++;            }        }        int index = colors.length - 1;          int curK = k;          while(index >= 0)         {              while(colors[curK - 1] < 0)             {                  colors[index--] = curK;                  if(index + 1 != curK - 1)                  {                    colors[curK - 1]++;                 }            }              curK--;         }    }    private void swap(int[] colors, int a, int b)     {          int tmp = colors[a];          colors[a] = colors[b];          colors[b] = tmp;      }  }

Last Update 2016.10.17

0 0
原创粉丝点击