Skip to content

Commit

Permalink
leetcode 85
Browse files Browse the repository at this point in the history
  • Loading branch information
Tanish2409 committed Jul 25, 2021
1 parent 10b8738 commit 75e6f37
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions leetcode/75_sort_colors.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#include<bits/stdc++.h>
using namespace std;

// Solution 1 - Sort Using merge sort - Time O(nlogn)
// Solution 2 - Using counting sort - Time O(2N) - i.e. requires 2 passes

// --------------------------------------------- Optimal Solution - Dutch National Flag Algo | Time O(n) | Space - O(1)
void sortColors(vector<int>& nums) {
int low = 0, mid = 0, high = nums.size() - 1;

while(mid <= high) {
switch (nums[mid])
{
case 0:
swap(nums[low++], nums[mid++]);
break;
case 1:
mid++;
break;
case 2:
swap(nums[mid], nums[high--]);
break;
}
}
}

int main() {
int n;
vector<int> nums;
cin>>n;


for(int i = 0; i < n; i++){
int x;
cin>>x;
nums.emplace_back(x);
}

sortColors(nums);

for(auto it: nums){
cout<<it<<" ";
}
}

0 comments on commit 75e6f37

Please sign in to comment.