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

Sort Colors

时间:2015-10-21 13:53:18      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:

 

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 class Solution {
 2     public void sortColors(int[] nums) 
 3     {
 4         int len = nums.length;
 5         if(nums==null||nums.length<=1)return;
 6         
 7         int left = 0;
 8         int right = len-1;
 9         int i = 0;
10         while(i<=right)
11         {
12             if(nums[i]==0)
13             {
14                 swap(nums,left,i);
15                 left++;
16                 i++;
17             }
18             else if(nums[i]==1)
19             {
20                 i++;
21             }
22             else 
23             {
24                 swap(nums,right,i);
25                 right--;
26                 //i++;
27             }
28         }
29         
30         return;
31         
32     }
33     
34     public void swap (int[] nums, int p, int i)
35     {
36         int temp = nums[p];
37         nums[p]=nums[i];
38         nums[i]=temp;
39     }
40 }

 

Sort Colors

标签:

原文地址:http://www.cnblogs.com/hygeia/p/4897430.html

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