LC.75. Sort Colors

https://leetcode.com/problems/sort-colors/description/
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.


 1 public void sortColors(int[] nums) {
 2         /*
 3         this is rainbow sort:
 4         (-inf, i) val = 0  swap i++ j++
 5         [i,j) val = 1       no swap  j++
 6         (k, +inf) val = 2    swap, k--
 7         [j, k] unknown area
 8         use the j as counter
 9         * */
10         if (nums == null || nums.length ==0) return;
11         int i =0 , j = 0, k = nums.length-1 ;
12         while (j<=k){
13             if (nums[j] == 0 ){
14                 swap(nums, i, j);
15                 i++;
16                 j++;
17             }else if(nums[j] == 1){
18                 j++;
19             } else{
20                 swap(nums,j,k);
21                 k--;
22             }
23         }
24     }
25     private void swap(int[] nums, int left, int right){
26         int temp = nums[left];
27         nums[left] = nums[right];
28         nums[right] = temp ;
29     }

 

posted @ 2018-03-13 05:46  davidnyc  阅读(159)  评论(0编辑  收藏  举报