735. Asteroid Collision

Posted Zzz...y

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 };

 

以上是关于735. Asteroid Collision的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 735. Asteroid Collision

Leetcode 735. Asteroid Collision

[LeetCode] Asteroid Collision 行星碰撞

小行星碰撞 Asteroid Collision

LeetCode 0735.行星碰撞:两种方法(方法二是方法一的优化)

Codeforces Round #735 (Div. 2)-C. Mikasa-题解