|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 |
| -/** Given an array with n objects colored red, white or blue, |
| 3 | +/** |
| 4 | + * 75. Sort Colors |
| 5 | + * |
| 6 | + * Given an array with n objects colored red, white or blue, |
4 | 7 | * sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
|
5 | 8 |
|
6 | 9 | Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
|
|
9 | 12 | You are not suppose to use the library's sort function for this problem.
|
10 | 13 |
|
11 | 14 | Follow up:
|
| 15 | +
|
12 | 16 | A rather straight forward solution is a two-pass algorithm using counting sort.
|
13 | 17 | First, iterate the array counting number of 0's, 1's, and 2's,
|
14 | 18 | then overwrite array with total number of 0's, then 1's and followed by 2's.
|
| 19 | + Could you come up with an one-pass algorithm using only constant space? |
| 20 | + */ |
15 | 21 |
|
16 |
| - Could you come up with an one-pass algorithm using only constant space?*/ |
17 | 22 | public class _75 {
|
18 | 23 |
|
| 24 | + public static class Solution1 { |
19 | 25 | public void sortColors(int[] nums) {
|
20 |
| - int zero = 0; |
21 |
| - int two = nums.length - 1; |
22 |
| - for (int i = 0; i <= two; ) { |
23 |
| - if (nums[i] == 0 && i > zero) { |
24 |
| - swap(nums, i, zero++); |
25 |
| - } else if (nums[i] == 2 && i < two) { |
26 |
| - swap(nums, i, two--); |
27 |
| - } else { |
28 |
| - i++; |
29 |
| - } |
| 26 | + int zero = 0; |
| 27 | + int two = nums.length - 1; |
| 28 | + for (int i = 0; i <= two; ) { |
| 29 | + if (nums[i] == 0 && i > zero) { |
| 30 | + swap(nums, i, zero++); |
| 31 | + } else if (nums[i] == 2 && i < two) { |
| 32 | + swap(nums, i, two--); |
| 33 | + } else { |
| 34 | + i++; |
30 | 35 | }
|
| 36 | + } |
31 | 37 | }
|
32 | 38 |
|
33 | 39 | void swap(int[] nums, int m, int n) {
|
34 |
| - int temp = nums[m]; |
35 |
| - nums[m] = nums[n]; |
36 |
| - nums[n] = temp; |
37 |
| - } |
38 |
| - |
39 |
| - |
40 |
| - public static void main(String... args) { |
41 |
| -// int[] nums = new int[]{0,1,2,0,2,1}; |
42 |
| -// int[] nums = new int[]{0}; |
43 |
| -// int[] nums = new int[]{2}; |
44 |
| - int[] nums = new int[]{2, 2, 1}; |
45 |
| -// int[] nums = new int[]{1,0}; |
| 40 | + int temp = nums[m]; |
| 41 | + nums[m] = nums[n]; |
| 42 | + nums[n] = temp; |
46 | 43 | }
|
| 44 | + } |
47 | 45 | }
|
0 commit comments