详细见:leetcode.com/problems/sort-colors
Java Solution: github
package leetcode;
public class P075_SortColors {
public static void main(String[] args) {
// int[] in = new int[] {1, 2, 1, 0, 1, 2, 0, 1, 2};
// int[] in = new int[] {2, 1, 1, 1, 0, 1, 1, 1, 1};
int[] in = new int[] {0, 0};
new Solution().sortColors(in);
tools.Utils.printArray(in, 10);
}
/*
* WA了一次,在第一次写条件的时候,尽量写全一点
* 1 ms
*/
static class Solution {
public void sortColors(int[] nums) {
if (nums == null || nums.length < 2)
return;
int sti = 0, eni = nums.length - 1, mid = 0;
boolean isDone = false;
while (! isDone) {
while (eni >= sti && nums[eni] == 2)
eni --;
while (sti <= eni && nums[sti] == 0)
sti ++;
if (sti >= eni)
isDone = true;
if (isDone) break;
if (nums[sti] == 2) {
swap(nums, sti, eni);
eni --;
} else if (nums[eni] == 0) {
swap(nums, sti, eni);
sti ++;
} else {
mid = sti + 1;
while (nums[mid] == 1) {
mid ++;
if (mid >= eni) {
isDone = true;
break;
}
}
if (isDone) break;
if (nums[mid] == 0) {
swap(nums, sti, mid);
sti ++;
} else if (nums[mid] == 2) {
swap(nums, mid, eni);
eni --;
}
}
}
}
void swap(int[] nums, int i , int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
}
C Solution: github
/*
url: leetcode.com/problems/sort-colors/
setColors: AC 3ms 0.00%
setColors2: AC 3ms 0.00%
*/
#include <stdio.h>
#include <stdlib.h>
void sortColors(int* n, int nn) {
int cnt_0 = 0, cnt_1 =0, cnt_2 = 0;
int i = 0, ni = 0;
for (i = 0; i < nn; i ++) {
if (n[i] == 0) cnt_0 ++;
if (n[i] == 1) cnt_1 ++;
if (n[i] == 2) cnt_2 ++;
}
for (i = 0; i < cnt_0; i ++)
n[ni ++] = 0;
for (i = 0; i < cnt_1; i ++)
n[ni ++] = 1;
for (i = 0; i < cnt_2; i ++)
n[ni ++] = 2;
}
void swap(int* a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
void sortColors2(int* n, int nn) {
int i = 0, j = nn - 1;
int i2 = nn-1, i0 = 0;
for (i = 0; i <= i2; i ++) {
while (i<i2 && n[i]==2) swap(n+i, n+(i2--));
while (i>i0 && n[i]==0) swap(n+i, n+(i0++));
}
}
Python Solution: github
#coding=utf-8
'''
url: leetcode.com/problems/set-matrix-zeroes/
@author: zxwtry
@email: zxwtry@qq.com
@date: 2017年4月17日
@details: Solution: 78ms 5.45%
'''
class Solution(object):
def sortColors(self, n):
"""
:type n: List[int]
:rtype: void Do not return anything, modify n in-place instead.
"""
if n == None or len(n) == 0: return
c0, c1, c2 = 0, 0, 0
for val in n:
if val == 0: c0 += 1
if val == 1: c1 += 1
if val == 2: c2 += 1
for i in range(c0):
n[i] = 0
for i in range(c1):
n[c0+i] = 1
for i in range(c2):
n[c0+c1+i] = 2