1. 程式人生 > >735. Asteroid Collision

735. Asteroid Collision

spa nts ever array left [] plan turn row

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 };

735. Asteroid Collision