Sort Colors
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

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

click to show follow up.

Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.

Could you come up with an one-pass algorithm using only constant space?

LeetCode: Sort Colors 解题报告

Solution 1:

类似radix sort, 先扫描一次得知所有的值出现的次数,再依次setup它们即可

ref: http://blog.csdn.net/fightforyourdream/article/details/15025713

http://en.wikipedia.org/wiki/Radix_sort

Radix sort

From Wikipedia, the free encyclopedia
Radix sort
Class Sorting algorithm
Data structure Array
Worst case performance LeetCode: Sort Colors 解题报告
Worst case space complexity LeetCode: Sort Colors 解题报告

In computer science, radix sort is a non-comparative integer sorting algorithm that sorts data with integer keys by grouping keys by the individual digits which share the same significant position and value. A positional notation is required, but because integers can represent strings of characters (e.g., names or dates) and specially formatted floating point numbers, radix sort is not limited to integers. Radix sort dates back as far as 1887 to the work of Herman Hollerith on tabulating machines.[1]

 1 public void sortColors1(int[] A) {
 2         if (A == null || A.length == 0) {
 3             return;
 4         }
 5         
 6         int len = A.length;
 7         
 8         int red = 0;
 9         int white = 0;
10         int blue = 0;
11         
12         for (int i = 0; i < len; i++) {
13             if (A[i] == 0) {
14                 red++;    
15             } else if (A[i] == 1) {
16                 white++;
17             } else {
18                 blue++;
19             }
20         }
21         
22         for (int i = 0; i < len; i++) {
23             if (red > 0) {
24                 A[i] = 0;
25                 red--;
26             } else if (white > 0) {
27                 A[i] = 1;
28                 white--;
29             } else {
30                 A[i] = 2;
31             }
32         }
33     }
View Code

相关文章:

  • 2021-10-12
  • 2021-05-27
  • 2021-12-12
  • 2021-07-01
猜你喜欢
  • 2021-10-28
  • 2021-05-18
  • 2022-02-06
  • 2021-05-19
  • 2022-01-19
  • 2021-12-23
  • 2021-08-21
相关资源
相似解决方案