Skip to content

Commit 7058f43

Browse files
committed
add solution of problem 75: sort colors
1 parent 44bf19c commit 7058f43

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

SortColors75/README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
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.
2+
3+
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
4+
5+
Note:
6+
You are not suppose to use the library's sort function for this problem.

SortColors75/Solution.java

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
public class Solution {
2+
public void sortColors(int[] nums) {
3+
if (nums == null)
4+
return;
5+
6+
int left = 0;
7+
int right = nums.length - 1;
8+
9+
//step one
10+
int idxFirstOne = sort(nums, left, right, 0);
11+
12+
//step two
13+
right = nums.length - 1;
14+
sort(nums, idxFirstOne, right, 1);
15+
}
16+
17+
private final int sort(int nums[], int left, int right, int pivot) {
18+
while (left < right) {
19+
while (left < right && nums[left] == pivot) {
20+
left++;
21+
}
22+
23+
while (left < right && nums[right] != pivot) {
24+
right--;
25+
}
26+
27+
if (left < right) {
28+
int tmp = nums[left];
29+
nums[left] = nums[right];
30+
nums[right] = tmp;
31+
}
32+
}
33+
34+
return left;
35+
}
36+
}

0 commit comments

Comments
 (0)