# LeetCode Sort Colors(排序)

314人阅读 评论(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.

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?

public class Solution {
public void sortColors(int[] nums) {
int left = 0, right = nums.length - 1;

while (left <= right && nums[left] == 0) left++;
while (right >= 0 && nums[right] == 2) right--;

if (left >= right) return;

int tmp;
int a = left;
while (a <= right) {
if (nums[a] == 0) {
tmp = nums[a];
nums[a] = nums[left];
nums[left] = tmp;
a++;
left++;
} else if (nums[a] == 2) {
tmp = nums[right];
nums[right] = nums[a];
nums[a] = tmp;
while (nums[right] == 2) right--;
if (nums[a] == 1) a++;
} else a++;
}
}
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：722265次
• 积分：18830
• 等级：
• 排名：第472名
• 原创：1235篇
• 转载：226篇
• 译文：0篇
• 评论：26条
博客专栏
 算法笔记 文章：12篇 阅读：9777
 网络编程学习笔记 文章：47篇 阅读：36969
评论排行
最新评论