-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsortcolors.cpp
52 lines (42 loc) · 975 Bytes
/
sortcolors.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// since we need the SC: O(1), we can't use any sorting algo, that's why we use this approach also known as Duth National Fla Approach
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
vector<int> sortColors(vector<int>& nums) {
int n = nums.size();
int i = 0;
int j = 0;
int k = n-1;
while (j<=k)
{
if(nums[j]==1)
j++;
else if(nums[j]==2){
swap(nums[j], nums[k]);
k--;
}
else{
swap(nums[j], nums[i]);
i++;
j++;
}
}
return nums;
}
};
int main(){
vector<int> nums = {2,0,2,1,1,0};
vector<int> ans;
Solution obj;
ans = obj.sortColors(nums);
for (int i = 0; i < nums.size(); i++)
{
cout << ans[i] << ", ";
}
cout << endl;
return 0;
}
// TC: O(n)
// SC: O(1)