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.
Example 1:
Input: asteroids = [5, 10, -5] Output: [5, 10] Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
Example 2:
Input: asteroids = [8, -8] Output: [] Explanation: The 8 and -8 collide exploding each other.
模拟小行星运动,正数表示往右走,负数表示往左走。碰撞时,体积小的消失。当两者体积一样,一起消失。
解决:按顺序依次把数据放进去就行。当放进去的数是负的,并且栈顶是正数,需要进行比较。
1 class Solution { 2 public: 3 vector<int> asteroidCollision(vector<int>& asteroids) { 4 vector<int> res; 5 if (asteroids.size()) { 6 for (auto as:asteroids) { 7 if (as<0) { 8 while(res.size() && res.back()>0 && as!=0){ 9 if(res.back()+as<0) 10 res.pop_back(); 11 else if(res.back()+as>0) 12 as = 0; 13 else { 14 res.pop_back(); 15 as = 0; 16 } 17 } 18 if((res.empty() || res.back()<0) && as!=0) res.push_back(as); 19 } 20 else 21 res.push_back(as); 22 } 23 } 24 return res; 25 } 26 };