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

Commit 9754772

Browse files
Refactor sortColors method to implement 2-pointer approach for improved efficiency
1 parent f24ae08 commit 9754772

File tree

1 file changed

+43
-18
lines changed

1 file changed

+43
-18
lines changed

‎leetcode/75.sort_colors.dart

Lines changed: 43 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -11,29 +11,54 @@ void main() {
1111
}
1212

1313
class Solution {
14-
////! Accepted From the first time TC: O(N) SC: O(1)
14+
////! Better Accepted From the first time TC: O(N) ----- SC: O(1)
15+
////! 2 Pointers Sort
1516
void sortColors(List<int> nums) {
16-
int zerosCount = 0;
17-
int onesCount = 0;
18-
for (var i = 0; i < nums.length; i++) {
19-
if (nums[i] ==0) {
20-
zerosCount++;
21-
} elseif (nums[i] == 1) {
22-
onesCount++;
23-
}
24-
}
25-
for (var i =0; i < nums.length; i++) {
26-
if (zerosCount >0) {
27-
nums[i] =0;
28-
zerosCount--;
29-
} elseif (onesCount >0) {
30-
nums[i] = 1;
31-
onesCount--;
17+
int rightIndex = nums.length -1;
18+
int leftIndex = 0;
19+
int midIndex = 0;
20+
int temp =0;
21+
while (midIndex <= rightIndex) {
22+
if (nums[midIndex] == 0) {
23+
temp = nums[leftIndex];
24+
nums[leftIndex] =0;
25+
nums[midIndex] = temp;
26+
leftIndex++;
27+
if (midIndex <= leftIndex) midIndex++;
28+
} elseif (nums[midIndex] ==2) {
29+
temp = nums[rightIndex];
30+
nums[rightIndex] =2;
31+
nums[midIndex] = temp;
32+
rightIndex--;
3233
} else {
33-
nums[i] =2;
34+
midIndex++;
3435
}
3536
}
3637
}
38+
39+
////! Accepted From the first time TC: O(2N) -- TC: O(N) SC: O(1)
40+
// void sortColors(List<int> nums) {
41+
// int zerosCount = 0;
42+
// int onesCount = 0;
43+
// for (var i = 0; i < nums.length; i++) {
44+
// if (nums[i] == 0) {
45+
// zerosCount++;
46+
// } else if (nums[i] == 1) {
47+
// onesCount++;
48+
// }
49+
// }
50+
// for (var i = 0; i < nums.length; i++) {
51+
// if (zerosCount > 0) {
52+
// nums[i] = 0;
53+
// zerosCount--;
54+
// } else if (onesCount > 0) {
55+
// nums[i] = 1;
56+
// onesCount--;
57+
// } else {
58+
// nums[i] = 2;
59+
// }
60+
// }
61+
// }
3762
}
3863

3964
void runTests() {

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /