C:
void dealLeft(int *asteroids, int size, int point) { if (point >= size) return; if (asteroids[point] >= 0) return; int left = point - 1; while (left >= 0 && asteroids[left] == 0) left--; if (left == -1 || asteroids[left] < 0) return; if (asteroids[point] + asteroids[left] > 0) asteroids[point] = 0; else if (asteroids[point] + asteroids[left] < 0) { asteroids[left] = 0; dealLeft(asteroids, size, point); } else asteroids[left] = asteroids[point] = 0; } /** * Note: The returned array must be malloced, assume caller calls free(). */ int *asteroidCollision(int *asteroids, int asteroidsSize, int *returnSize) { for (int i = 0; i < asteroidsSize; i++) { dealLeft(asteroids, asteroidsSize, i); } int size = 0; for (int i = 0; i < asteroidsSize; i++) if (asteroids[i] != 0) size++; *returnSize = size; if (size > 0) { int *reArr = (int *)malloc(sizeof(int) * size); int point = 0; for (int i = 0; i < asteroidsSize; i++) if (asteroids[i] != 0) { reArr[point] = asteroids[i]; point++; } return reArr; } else return NULL; }
JAVA:
public final int[] asteroidCollision(int[] asteroids) { for (int i = 0; i < asteroids.length; i++) { searchLeft(asteroids, i); } int len = 0, point = 0; for (int i = 0; i < asteroids.length; i++) if (asteroids[i] != 0) len++; int[] reArr = new int[len]; for (int i = 0; i < asteroids.length; i++) { if (asteroids[i] != 0) { reArr[point] = asteroids[i]; point++; } } return reArr; } private final void searchLeft(int[] asteroids, int point) { if (asteroids[point] > 0) return; int left = point - 1; while (left >= 0 && asteroids[left] == 0) left--; if (left == -1 || asteroids[left] < 0) return; if (asteroids[left] + asteroids[point] > 0) asteroids[point] = 0; else if (asteroids[left] + asteroids[point] < 0) { asteroids[left] = 0; searchLeft(asteroids, point); } else { asteroids[point] = 0; asteroids[left] = 0; } }
JS:
/** * @param {number[]} asteroids * @return {number[]} */ var asteroidCollision = function (asteroids) { for (let i = 0; i < asteroids.length; i++) dealLeft(asteroids, i); let reArr = []; for (let i = 0; i < asteroids.length; i++) if (asteroids[i]) reArr.push(asteroids[i]); return reArr; }; //处理左边反向的 var dealLeft = function (asteroids, point) { if (asteroids[point] > 0) return; let left = point - 1; while (left >= 0 && asteroids[left] == 0) left--; if (left == -1 || asteroids[left] < 0) return; if (asteroids[left] + asteroids[point] > 0) asteroids[point] = 0; else if (asteroids[left] + asteroids[point] < 0) { asteroids[left] = 0; dealLeft(asteroids, point); } else { asteroids[left] = 0; asteroids[point] = 0; } }