-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAsteroidCollision_735.cpp
More file actions
31 lines (26 loc) · 899 Bytes
/
AsteroidCollision_735.cpp
File metadata and controls
31 lines (26 loc) · 899 Bytes
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
/*
~ Author : https://leetcode.com/tridib_2003/
~ Problem : 735. Asteroid Collision
~ Link : https://leetcode.com/problems/asteroid-collision/
*/
class Solution {
public:
vector<int> asteroidCollision(vector<int>& asteroids) {
vector<int> res;
for (int i = 0; i < asteroids.size(); ++i) {
if (asteroids[i] > 0)
res.emplace_back(asteroids[i]);
else {
while (!res.empty() && res.back() > 0 && res.back() < abs(asteroids[i]))
res.pop_back();
if (res.empty() || res.back() < 0)
res.emplace_back(asteroids[i]);
else if (!res.empty() && res.back() == abs(asteroids[i]))
res.pop_back();
}
}
return res;
}
};
// Time Complexity - O(n)
// Auxiliary Space - O(n)