forked from DeepanshuProgrammer/GeeksforGeeks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
27 August "Problem of the Day" Answer
98 lines (78 loc) · 2.57 KB
/
27 August "Problem of the Day" Answer
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
GeeksforGeeks
The Question is :- "Alternate positive and negative numbers"
Answer :-
class Solution{
public:
void rearrange(int arr[], int n) {
// code here
//check for the efficient soln.
//wht i did here is
//As we have time and space complexity as N
//we can stroe them, in another arrays and do the normal answer.
//so wht i did is
//i stored both the positive and neg elenmnts in the queues, not vectors bczo
//if queue, thn we remove the elements at top, with out using the indices, we can just use the key word, pop
//and for pushing also, we just need to use push,
//but where as for the vectors, we need to use the indeices to acces the elements
//and also to delete thm, it will b difficult.
//so, after storing thm in the queues, wht i did is
//first as it was mentioned, we need positive first,
//we will start with the pos elements only.
//so, we will run the loop, n times only.
//this only better coz, we know, how many times, we hav to run.
//thn each time, if i is even, thn and if pos not empty.
//we replace the arra element as pos.front
//and pop.
//if pos empty, thn we wcheck for the neg elemnt
//thn we will pop frm neg elemmt.
//similarly, we do like this for the i whn they r not divided by 2.
//in tht case, alos
//if neg not emty, thn we pop.
//if empty, thn we pop frm the pos if thts not empty.
//thts it.
queue<int> pos,neg;
for(int i=0;i<n;i++)
{
if(arr[i] < 0)
{
neg.push(arr[i]);
}
else
{
pos.push(arr[i]);
}
}
for(int i=0;i<n;i++)
{
if(i%2 == 0)
{
if(!pos.empty())
{
arr[i] = pos.front();
pos.pop();
}
else
{
arr[i] = neg.front();
neg.pop();
}
}
else
{
if(!neg.empty())
{
arr[i] = neg.front();
neg.pop();
}
else
{
arr[i] = pos.front();
pos.pop();
}
}
}
}
};
Hope you understand the answer, and complete it.
Stay Connected for daily Problem of the Day answers.
Thank you All!