leetcode 735. Asteroid Collision

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Sea_muxixi/article/details/79957786

leetcode 735. Asteroid Collision

题意:给你一个数组,正数会往右移,负数会往左移,移动速度一样,两个数字相撞的话,绝对值大的数会破坏绝对值小的数,问你最后数组的状态。

模拟一下,应该不难。

class Solution {
public:
	vector<int> asteroidCollision(vector<int>& asteroids) {
		stack<int> ans;
		for (int i = 0; i<asteroids.size(); i++)
		{
			if (ans.empty()) ans.push(asteroids[i]);
			else
			{
				if (ans.top() < 0 && asteroids[i] < 0)
					ans.push(asteroids[i]);
				else if (ans.top() > 0 && asteroids[i] > 0)
					ans.push(asteroids[i]);
				else if (ans.top() < 0 && asteroids[i] > 0)
					ans.push(asteroids[i]);
				else if (ans.top() > 0 && asteroids[i] < 0)
                                { 
                                        int flag = 1;
					while (!ans.empty())
					{
						int num = ans.top();
						if (num > 0 && num < abs(asteroids[i]))// 
						{
							ans.pop();
						}
						else if (num > 0 && num > abs(asteroids[i]))
						{
							flag = 0;
							break;
						}
						else if (num > 0 && num == abs(asteroids[i]))
						{
							flag = 0;
							ans.pop();
							break;
						}
                                                else if (num < 0)
						{
							break;
						}
					}
					if (flag == 1) ans.push(asteroids[i]);
				}
			}
		}
		int size = ans.size();
		vector<int> aans(size);
		size--;
		while (!ans.empty())
		{
			aans[size--] = ans.top();
			ans.pop();
		}
		return aans;
	}
};

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页