Leet - 735

Having fun on Leetcode with C++, Java, Python & GO

Problem 735. Asteroid Collision

My attempt(s)

Code

C++

 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
class Solution {
public:
    vector<int> asteroidCollision(vector<int>& asteroids)     {
        for (int i=0; i<asteroids.size(); i++){
            if (asteroids[i]<0){
                for (int j=i-1; j>-1; j--){
                    if (asteroids[j]>0){
                        if ((asteroids[i]*-1)>asteroids[j])
                            asteroids[j]=0;
                        else if ((asteroids[i]*-1)<asteroids[j]){
                            asteroids[i]=0;
                            break;
                        }
                        else{
                            asteroids[i]=0;
                            asteroids[j]=0;
                            break;
                        }
                    }
                }
            }
        }
        asteroids.erase(remove(asteroids.begin(), asteroids.end(), 0), asteroids.end()); 
        return(asteroids);
    }
};

Explanation of idea

Good solution ref.

Code

Analysis

Licensed under CC BY-NC-SA 4.0