LeetCode Sort Colors(排序)

﻿﻿
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++;
}
}
}

• 本文已收录于以下专栏：

LeetCode-Sort Colors-排序

Sort Colors Java 排序 Given an array with n objects colored red, white or blue, sort them so that obj...
• KINGHMY
• 2016年09月12日 21:41
• 223

LeetCode-75. Sort Colors (JAVA)三色排序

LeetCode-75. Sort Colors (JAVA)三色排序

【LeetCode-面试算法经典-Java实现】【075-Sort Colors （颜色排序）】

【075-Sort Colors （颜色排序）】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题　　Given an array with n objects colored ...

LeetCode 75 Sort Colors

Given an array with n objects colored red, white or blue, sort them so that objects of the same colo...

[leetCode 75] Sort Colors

• ever223
• 2015年03月20日 14:38
• 784

Leetcode_75_Sort Colors

Given an array with n objects colored red, white or blue, sort them so that objects of the same colo...

【leetcode 数组】Sort Colors

1、题目 2、分析 3、代码

举报原因： 您举报文章：LeetCode Sort Colors(排序) 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)