Skip to content

Commit 472f969

Browse files
refactor 75
1 parent d3c3bab commit 472f969

File tree

1 file changed

+18
-37
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+18
-37
lines changed
Lines changed: 18 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,26 @@
11
package com.fishercoder.solutions;
22

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-
223
public class _75 {
234

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+
}
3518
}
36-
}
37-
}
3819

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+
}
4325
}
44-
}
4526
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy