Lintcode - sort colors II

来源:互联网 发布:南京品浪钓具淘宝店铺 编辑:程序博客网 时间:2024/06/09 14:28

Given an array of n objects with k different colors (numbered from 1 to k), sort them so that objects of the same color are adjacent, with the colors in the order 1, 2, ... k.

Note

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

Example

GIven colors=[3, 2, 2, 1, 4], k=4, your code should sort colors in-place to [1, 2, 2, 3, 4]. 

Challenge

A rather straight forward solution is a two-pass algorithm using counting sort. That will cost O(k) extra memory.

Can you do it without using extra memory?

为了省空间,只能花时间了,还是按照sort color的方法,找到当前array中min, max,其余忽略,然后把min/max放到最前和最后。循环直到min/max count = k

复杂度是O(n^2): T(n) = T(n-2) + n


    public void sortColors2(int[] colors, int k) {        int count = 0;        int start = 0;        int end = colors.length-1;        while (count < k) {            int min = Integer.MAX_VALUE;            int max = Integer.MIN_VALUE;                        for (int i = start; i < end; i++) {                min = Math.min(min, colors[i]);                max = Math.max(max, colors[i]);            }            int left = start;            int right = end;            int cur = left;            while(cur <= right) {                if (colors[cur] == min) {                    swap(left, cur, colors);                    cur++;                    left++;                } else if (colors[cur] > min && colors[cur] < max) {                    cur++;                } else {                    int tmp = colors[cur];                    swap(cur, right, colors);                    right--;                }            }            count += 2;            start = left;            end = right;        }    }        void swap(int left, int right, int[] colors) {        int tmp = colors[left];        colors[left] = colors[right];        colors[right] = tmp;    }


0 0