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.
Have you met this question in a real interview?
Yes
Example
Given colors=[3, 2, 2, 1, 4]
, k=4
, your code should sort colors in-place to [1, 2, 2, 3, 4]
.
Note
You are not suppose to use the library's sort function for this problem.
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?
Solution:
public void sortColors2(int[] colors, int k) { int n = colors.length; int[] B = new int[n]; int[] C = new int[k+1]; for(int a:colors) C[a]++; for(int i=1; i<=k; i++) { C[i] += C[i-1]; } for(int a:colors) { C[a]--; B[C[a]] = a; } System.arraycopy(B, 0, colors, 0, n); }
Reference:
https://zh.wikipedia.org/wiki/计数排序
http://www.geeksforgeeks.org/counting-sort/
https://www.cs.usfca.edu/~galles/visualization/CountingSort.html