Asteroid Collision
2024-09-05 12:19:40
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.
class Solution {
public int[] asteroidCollision(int[] a) {
LinkedList<Integer> s = new LinkedList<>();
for (int i = ; i < a.length; i++) {
if (a[i] > || s.isEmpty() || s.getLast() < ) {
s.add(a[i]);
} else if (s.getLast() == -a[i]) {
s.pollLast();
} else if (s.getLast() < -a[i]) {
s.pollLast();
i--; // very clever idea
}
}
return s.stream().mapToInt(i -> i).toArray();
}
}
最新文章
- GDB十分钟教程
- JS引用类型之——数组
- 【ASP.NET】获取网站目录的方法
- WPF获取控件的句柄
- TCP/IP协议原理与应用笔记16:交换机和路由器区别
- EF中使用SQL函数
- ashx调用session对象
- Ultimate thread group线程组和Stepping thread group线程组测试场景
- python-复杂生成式
- RSA加密传输代码示例
- tcp,Socket,三次握手和四次挥手的图示
- Tomcat线程数与处理速度的关系
- 【Gym 100733D】Little thief Shi(取数,DP)
- linux 下实用软件工具推荐
- Python 一些有趣的技巧,包括协程例
- Docker的概述
- 2018面向对象程序设计(Java)第6周学习指导及要求
- sift 与 surf 算法
- Eclipse 打包jar
- sql添加自动增长列