leetcode 735. Asteroid Collision 行星碰撞 + 类似括号配对 + 栈的典型应用

妖狐艹你老母 2022-06-03 09:44 233阅读 0赞

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.
Example 3:
Input:
asteroids = [10, 2, -5]
Output: [10]
Explanation:
The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.
Example 4:
Input:
asteroids = [-2, -1, 1, 2]
Output: [-2, -1, 1, 2]
Explanation:
The -2 and -1 are moving left, while the 1 and 2 are moving right.
Asteroids moving the same direction never meet, so no asteroids will meet each other.
Note:

The length of asteroids will be at most 10000.
Each asteroid will be a non-zero integer in the range [-1000, 1000]..

本题有点类似括号配对,直接使用栈即可完成,

代码如下:

  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <set>
  5. #include <queue>
  6. #include <stack>
  7. #include <string>
  8. #include <climits>
  9. #include <algorithm>
  10. #include <sstream>
  11. #include <functional>
  12. #include <bitset>
  13. #include <numeric>
  14. #include <cmath>
  15. #include <regex>
  16. using namespace std;
  17. class Solution
  18. {
  19. public:
  20. vector<int> asteroidCollision(vector<int>& a)
  21. {
  22. vector<int> res;
  23. int i = 0;
  24. while (i < a.size())
  25. {
  26. if (res.empty() || a[i]>0 || res.back()<0)
  27. res.push_back(a[i++]);
  28. else
  29. {
  30. if (res.back() < -a[i])
  31. res.pop_back();
  32. else if (res.back() > -a[i])
  33. i++;
  34. else
  35. {
  36. res.pop_back();
  37. i++;
  38. }
  39. }
  40. }
  41. return res;
  42. }
  43. };

发表评论

表情:
评论列表 (有 0 条评论,233人围观)

还没有评论,来说两句吧...

相关阅读

    相关 735 行星碰撞(模拟)

    1. 问题描述: 给定一个整数数组 asteroids,表示在同一行的行星。对于数组中的每一个元素,其绝对值表示行星的大小,正负表示行星的移动方向(正表示向右移动,负表示向左

    相关 括号配对问题

    描述 现在,有一行括号序列,请你检查这行括号是否配对。 输入 第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个

    相关 括号配对问题

    描述 现在,有一行括号序列,请你检查这行括号是否配对。 输入 第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都

    相关 括号配对问题

    括号配对问题,其实是栈的一个应用,很常见也很普通。 栈是最常见的和最重要的数据结构之一,用途非常广泛。它是一种只能在一端进行插入或删除操作的线性表,括号配对是栈的链式储存及