-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortByColor.cpp
More file actions
50 lines (45 loc) · 1.1 KB
/
SortByColor.cpp
File metadata and controls
50 lines (45 loc) · 1.1 KB
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
/*QUestion:
Sort by Color
Asked in:
Facebook
Microsoft
Given an array with n objects colored red, white or blue,
sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note: Using library sort function is not allowed.
Example :
Input : [0 1 2 0 1 2]
Modify array so that it becomes : [0 0 1 1 2 2]
*/
void Solution::sortColors(vector<int> &A) {
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details
int zc=0,oc=0,tc=0;
for(int i=0;i<A.size();i++)
{
if(A[i]==0)
zc++;
else if(A[i]==1)
oc++;
else
tc++;
}
int i=0;
while(zc--)
{
A[i]=0;
i++;
}
while(oc--)
{
A[i]=1;
i++;
}
while(tc--)
{
A[i]=2;
i++;
}
}