-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathasteroidCollision.cpp
More file actions
83 lines (69 loc) · 1.9 KB
/
asteroidCollision.cpp
File metadata and controls
83 lines (69 loc) · 1.9 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
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
// https://leetcode.com/problems/asteroid-collision/
//
// Status: Accepted
// Runtime: 24 ms
// Score: 71.64 %
//
#include <iostream>
#include <vector>
#include <gtest/gtest.h>
#include "args.h"
#include "macros.h"
using namespace std;
class Solution
{
public:
vector<int> asteroidCollision(vector<int> &asteroids)
{
// Abs.value = size;
// if a>b, b is removed
// if a==b, both are removed
// if b>a, a is removed
//
// If positive, moving to right
// If negative, moving to left
// Maybe check if asteroid is 0, not sure what
// to do in that case, behavior is undefined
std::vector<int> states;
for (auto a : asteroids)
{
bool done = false;
while (!done)
{
// check previous entry to see if these two
// will collide
if (states.empty())
{
states.push_back(a);
break;
}
auto b = states.back();
// if moving in same direction then no collision
if (!((a < 0) && (b > 0)))
{
states.push_back(a);
break;
}
// they are going to collide, see who survives
if (abs(a) >= abs(b))
{
// Nuke b, keep a. I can actually add this
// back to asteroids list
states.pop_back();
}
if (abs(a) <= abs(b))
{
done = true;
}
}
}
return states;
}
};
TEST(AsteroidCollision, Example)
{
Solution solution;
vector<int> asteroids{5, 10, -5};
vector<int> expected{5, 10};
ASSERT_EQ(solution.asteroidCollision(asteroids), expected);
}