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

75. Sort Colors(荷兰国旗问题 三指针)

时间:2018-02-20 23:34:41      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:sam   oid   ase   else   order   fun   object   res   while   

 

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 class Solution {
 2     public void sortColors(int[] nums) {
 3         int begin  = 0;
 4         int cur = 0;
 5         int end = nums.length-1;
 6         while(cur<=end){
 7             if(nums[cur]==2){
 8                 swap(nums,cur,end);
 9                 end--;
10             }
11             else if(nums[cur]==1){
12                 cur++;
13             }
14             else //(nums[cur]==0)
15             {
16                 if(nums[cur]!=nums[begin])
17                     swap(nums,cur,begin);
18                 begin++;
19                 cur++;
20             }
21         }
22     }
23     private void swap(int[] nums,int i ,int j){
24         int temp;
25         temp = nums[i];
26         nums[i] = nums[j];
27         nums[j] = temp;
28     }
29 }

 

75. Sort Colors(荷兰国旗问题 三指针)

标签:sam   oid   ase   else   order   fun   object   res   while   

原文地址:https://www.cnblogs.com/zle1992/p/8455978.html

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