leetcode [#75]

目录

题目

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class Solution {
public void sortColors(int[] nums) {
int N = nums.length;
sort(nums, 0, N-1);
}
private void sort(int[] nums, int lo, int hi){
if(hi <= lo) return;

int j = partition(nums, lo, hi);
sort(nums, lo, j-1);
sort(nums, j+1, hi);
}
private int partition(int[] nums, int lo, int hi){
int i = lo;
int j = hi + 1;
int v = nums[lo];

while(true){
while (nums[++i] < v) if(i == hi) break;
while (nums[--j] > v) if(j == lo) break;
if(i >= j) break;

int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
int exch = nums[lo];
nums[lo] = nums[j];
nums[j] = exch;
return j;
}
}

注意事项

  1. 实现快速排序。