码迷,mamicode.com
首页 > 其他好文 > 详细

Sort Colors

时间:2015-11-01 19:17:33      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

1. Title

Sort Colors

2.   Http address

https://leetcode.com/problems/sort-colors/

3. The question

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.

4. My code (AC)

 1 // Accepted
 2     public static void sortColors(int []nums){
 3         if( nums == null || nums.length <= 1)
 4                 return;
 5         int len = nums.length;
 6         int i,j,tmp;
 7         i = 0; j = len -1;
 8         while(i < len && j >= i )
 9         {
10 
11             if( nums[i] == 0)
12             {
13                 i++;
14                 continue;
15             }
16 
17             if ( nums[j] != 0 )
18             {
19                 j--;    
20                 continue;
21             }
22 
23             tmp = nums[i];
24             nums[i] = nums[j];
25             nums[j] = tmp;
26             i++;
27             j--;
28         }
29 
30         i = 0;
31         while( i < len && nums[i] == 0)
32         {
33                 i++;
34         }
35         j = len-1;
36         while( i < len && j >= i)
37         {
38 
39             if( nums[i] == 1 )
40             {
41                 i++;
42                 continue;
43             }
44 
45             if(nums[j] == 2 )
46             {
47                 j--;
48                 continue;
49             }
50     
51             tmp = nums[i];
52             nums[i] = nums[j];
53             nums[j] = tmp;
54             i++;
55             j--;
56         }
57     }

 

Sort Colors

标签:

原文地址:http://www.cnblogs.com/ordili/p/4928336.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!