forked from begeekmyfriend/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: Leo Ma <[email protected]>
- Loading branch information
1 parent
e698e78
commit 0f3b43b
Showing
2 changed files
with
59 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
all: | ||
gcc -O2 -o test sort_colors.c |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
#include <stdio.h> | ||
#include <stdlib.h> | ||
#include <string.h> | ||
|
||
static void swap(int *a, int *b) | ||
{ | ||
int tmp = *a; | ||
*a = *b; | ||
*b = tmp; | ||
} | ||
|
||
/* | ||
* RED = 0 | ||
* WHITE = 1 | ||
* BLUE = 2 | ||
*/ | ||
static void sortColors(int* nums, int numsSize) { | ||
int i = 0, j = numsSize - 1; | ||
while (i < j) { | ||
while (nums[i] == 0 && i < j) { | ||
i++; | ||
} | ||
while (nums[j] != 0 && j > i) { | ||
j--; | ||
} | ||
swap(nums + i, nums + j); | ||
} | ||
j = numsSize - 1; | ||
while (i < j) { | ||
while (nums[i] == 1 && i < j) { | ||
i++; | ||
} | ||
while (nums[j] != 1 && j > i) { | ||
j--; | ||
} | ||
swap(nums + i, nums + j); | ||
} | ||
} | ||
|
||
int main(int argc, char **argv) | ||
{ | ||
if (argc != 2) { | ||
fprintf(stderr, "Usage: ./test colors\n"); | ||
exit(-1); | ||
} | ||
int i, count = strlen(argv[1]); | ||
int *nums = malloc(count * sizeof(int)); | ||
for (i = 0; i < count; i++) { | ||
nums[i] = argv[1][i] - '0'; | ||
} | ||
sortColors(nums, count); | ||
for (i = 0; i < count; i++) { | ||
printf("%d", nums[i]); | ||
} | ||
printf("\n"); | ||
return 0; | ||
} |