Lintcode: Sort Colors II, lintcodecolors

Source: Internet
Author: User
Tags lintcode

Lintcode: Sort Colors II, lintcodecolors

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.NoteYou are not suppose to use the library's sort function for this problem.ExampleGIven colors=[3, 2, 2, 1, 4], k=4, your code should sort colors in-place to [1, 2, 2, 3, 4]. ChallengeA 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?

First, I wrote an O (kN) time complexity and O (1) space complexity. This algorithm is suitable for the case where the number of colors is small (k is constant)

 1 class Solution { 2     /** 3      * @param colors: A list of integer 4      * @param k: An integer 5      * @return: nothing 6      */ 7     public void sortColors2(int[] colors, int k) { 8         // write your code here 9         if (colors==null || colors.length==0 || k<=1) return;10         int l=0, r=colors.length-1;11         int pivot = r;12             while (true) {13                 while (l<r && colors[l]<colors[pivot]) {14                     r--;15                 }16                 while (l<r && colors[l]==cnt) {17                     l++;18                 }19                 if (l == r) break;20                 swap(colors, l, r);21             }22             l++;23             r = colors.length-1;24             if (l == r) break;25     }26     27     public void swap(int[] colors, int l, int r) {28         int temp = colors[l];29         colors[l] = colors[r];30         colors[r] = temp;31     }32 }

If K-> N is used, the time complexity is high. Therefore, Quick Sort is used.

 1 class Solution { 2     /** 3      * @param colors: A list of integer 4      * @param k: An integer 5      * @return: nothing 6      */ 7     public void sortColors2(int[] colors, int k) { 8         // write your code here 9         if (colors==null || colors.length==0 || k<=1) return;10         quickSort(colors, 0, colors.length-1);11     }12     13     public void quickSort(int[] colors, int l, int r) {14         if (l >= r) return;15         int pivot = r;16         int pos = partition(colors, l, r, pivot);17         quickSort(colors, l, pos-1);18         quickSort(colors, pos+1, r);19     }20     21     public int partition(int[] colors, int start, int end, int pivot) {22         int l=start, r=end;23         while (true) {24             while (l<r && colors[l]<colors[pivot]) {25                 l++;26             }27             while (l<r && colors[r]>=colors[pivot]) {28                 r--;29             }30             if (l == r) break;31             swap(colors, l, r);32         }33         swap(colors, l, end);34         return l;35     }36     37     public void swap(int[] colors, int l, int r) {38         int temp = colors[l];39         colors[l] = colors[r];40         colors[r] = temp;41     }42 }

Someone on the Internet gave the O (N) solution.

Inplace and O (N) time complexity algorithms.

We can use the bucket sorting idea to count all the numbers.

1. Scan from left to right. If you encounter a number, first find the corresponding bucket. For example:

3 2 2 1 4

The bucket corresponding to the first 3 is index = 2 (the bucket starts from 0)

2. If the Bucket has a number, move the number to the position (that is, to store it) of I, and then mark the bucket as-1 (indicating that the position is a counter, counted as 1 ).

3. the Bucket stores a negative number, indicating that the bucket is already a counter, directly minus 1. Set color [I] to 0 (indicating that the Bucket has been computed here)

4. the Bucket stores 0, which is processed in the same way as 3. Set the bucket to-1 and color [I] to 0 (indicating that the Bucket has been computed here)

5. Return to position I and judge whether the value is 0. (If the value is not 0, repeat steps 2-4 ).

6. After completing steps 1-5, the array is set from the end to the header. (From the end to the header is to avoid overwrite the counter at the beginning)

Example (based on the above steps ):

3 2 2 1 4

2 2-1 1 4

2-1-1 1 4

0-2-1 1 4

-1-2-1 0 4

-1-2-1-1 0

 1 // Solution 2: inplace, O(n)  2     public void sortKColors(int[] colors, int k) { 3         // write your code here 4         if (colors == null) { 5             return; 6         } 7          8         int len = colors.length; 9         for (int i = 0; i < len; i++) {10             // Means need to deal with A[i]11             while (colors[i] > 0) {12                 int num = colors[i];13                 if (colors[num - 1] > 0) {    14                     // 1. There is a number in the bucket, 15                     // Store the number in the bucket in position i;16                     colors[i] = colors[num - 1];17                     colors[num - 1] = -1;18                 } else if (colors[num - 1] <= 0) {19                     // 2. Bucket is using or the bucket is empty.20                     colors[num - 1]--;21                     // delete the A[i];22                     colors[i] = 0;23                 }24             }25         }26         27         int index = len - 1;28         for (int i = k - 1; i >= 0; i--) {29             int cnt = -colors[i];30             31             // Empty number.32             if (cnt == 0) {33                 continue;34             }35                                 36             while (cnt > 0) {37                 colors[index--] = i + 1;38                 cnt--;39             }40         }

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.