xinyu04

导航

[Oracle] LeetCode 735. Asteroid Collision

We are given an array asteroids of integers representing asteroids in a row.

For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.

Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.

Solution

\(stack\) 模拟即可,不过需要想好细节

点击查看代码
class Solution {
private:
    vector<int> ans;
    stack<int> sk;
public:
    vector<int> asteroidCollision(vector<int>& ast) {
        int n = ast.size();
        for(int i=0;i<n;i++){
            if(sk.empty())sk.push(ast[i]);
            else{
                int cur = ast[i];
                if(sk.top()<0 && cur>0){ sk.push(cur);continue;}
                else if(sk.top()>0 && cur>0){sk.push(cur);continue;}
                else if(sk.top()<0 && cur<0) {sk.push(cur);continue;} 
                
                int fg=0;
                while(!sk.empty() && cur<0 && sk.top()>0 && (abs(sk.top())<abs(cur)) ){
                    sk.pop();
                }
                //cout<< sk.empty()<<endl;
                if(sk.empty()){sk.push(cur);continue;}
                if(cur*sk.top()>0){sk.push(cur);continue;}    
                if(abs(cur)<abs(sk.top()))continue;
                else if(abs(cur)==abs(sk.top()))sk.pop();
                    
            }
        }
        if(sk.empty())return ans;
        while(!sk.empty()){
            ans.push_back(sk.top());sk.pop();
        }
        reverse(ans.begin(), ans.end());
        return ans;
    }
};

posted on 2022-08-23 17:32  Blackzxy  阅读(14)  评论(0编辑  收藏  举报