Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit2701ec6

Browse files
authored
Merge pull requestneetcode-gh#1339 from julienChemillier/patch-26
Add 75 in c language
2 parents30fe2f4 +134968f commit2701ec6

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

‎c/75-Sort-Colors.c‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/*
2+
Given an array nums with n objects colored red, white, or blue, sort
3+
them in-place so that objects of the same color are adjacent, with
4+
the colors in the order red, white, and blue.
5+
6+
Space: O(1)
7+
Time: O(n) (one-pass algorithm)
8+
*/
9+
10+
11+
voidswap(int*nums,inta,intb) {
12+
inttmp=nums[a];
13+
nums[a]=nums[b];
14+
nums[b]=tmp;
15+
}
16+
17+
voidsortColors(int*nums,intnumsSize){
18+
intpos1=0;
19+
intright=numsSize-1;
20+
intleft=0;
21+
// Before index (left-pos1) -> only 0
22+
// Between indexes (left-pos1) and left -> only 1
23+
// After indexe left -> only 2
24+
while (left<=right) {
25+
if (nums[left]==2) {
26+
swap(nums,left,right);
27+
right--;
28+
}elseif (nums[left]==0) {
29+
swap(nums,left,left-pos1);
30+
left++;
31+
}else {
32+
pos1++;
33+
left++;
34+
}
35+
}
36+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp