import java.util.Arrays;
/**
* 行星碰撞问题
* We are given an array asteroids of integers representing asteroids in a row.
* <p>
* 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.
* <p>
* 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.
* <p>
* Example 1:
* <p>
* Input: asteroids = [5,10,-5]
* Output: [5,10]
* Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
* <p>
* Example 2:
* <p>
* Input: asteroids = [8,-8]
* Output: []
* Explanation: The 8 and -8 collide exploding each other.
* <p>
* Example 3:
* <p>
* Input: asteroids = [10,2,-5]
* Output: [10]
* Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.
* <p>
* Example 4:
* <p>
* 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.
* <p>
* Constraints:
* <p>
* 2 <= asteroids.length <= 10^4
* -1000 <= asteroids[i] <= 1000
* asteroids[i] != 0
*/
public class _735_AsteroidCollision {
public static void main(String[] args) {
_735_AsteroidCollision asteroidCollision = new _735_AsteroidCollision();
int[] arr = new int[]{5, 10, -5};
System.out.println(Arrays.toString(asteroidCollision.asteroidCollision(arr)));
arr = new int[]{8, -8};
System.out.println(Arrays.toString(asteroidCollision.asteroidCollision(arr)));
arr = new int[]{10, 2, -5};
System.out.println(Arrays.toString(asteroidCollision.asteroidCollision(arr)));
arr = new int[]{-2, -1, 1, 2};
System.out.println(Arrays.toString(asteroidCollision.asteroidCollision(arr)));
}
public int[] asteroidCollision(int[] asteroids) {
// 新分配数组从0开始赋值
int[] arr = new int[asteroids.length];
int index = 0;
// 当前数组是否有修改
boolean update = false;
for (int i = 0; i < asteroids.length; i++) {
int i1 = asteroids[i];
if (i + 1 == asteroids.length) { // 只剩一个行星
arr[index++] = i1;
} else {
int i2 = asteroids[i + 1];
if (i1 > 0 && i1 == -i2) { // 两行星对撞,相等则消失
i++;
update = true;
} else if (i1 > 0 && i2 < 0) { // 两行星对撞,不相等取大的
arr[index++] = i1 + i2 > 0 ? i1 : i2;
i++;
update = true;
} else { // 两行星不会对撞
arr[index++] = i1;
}
}
}
return update ?
// 有修改返回过滤之后的值
asteroidCollision(Arrays.copyOf(arr, index)) :
// 无修改直接返回对应数组
asteroids;
}
}
/* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步