File tree Expand file tree Collapse file tree 1 file changed +43
-18
lines changed
Expand file tree Collapse file tree 1 file changed +43
-18
lines changed Original file line number Diff line number Diff line change @@ -11,29 +11,54 @@ void main() {
1111}
1212
1313class 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- } else if (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- } else if (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+ } else if ( 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
3964void runTests () {
You can’t perform that action at this time.
0 commit comments