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