i >= 0这个条件,属于边界条件,不写会卡用例,1, -2, -2, -2。
import java.util.Arrays;
class Suit {
public static int[] asteroidCollision(int[] asteroids) {
int len = asteroids.length;
int size = len;
for (int i = 0; i < size - 1; i++) { // 屏蔽住 i--, 可以看到编译器显示的问题,并没有累加
if (i >= 0 && asteroids[i] > 0 && asteroids[i + 1] < 0) {// i >=0 卡测试用例1, -2, -2, -2
if (Math.abs(asteroids[i]) > Math.abs(asteroids[i + 1])) {
for (int j = i + 2; j < len; j++) {
asteroids[j - 1] = asteroids[j];
}
i--;
size--;
} else if (Math.abs(asteroids[i]) == Math.abs(asteroids[i + 1])) {
for (int j = i + 2; j < len; j++) {
asteroids[j - 2] = asteroids[j];
}
size -= 2;
i -= 2;
} else {
for (int j = i + 1; j < len; j++) {
asteroids[j - 1] = asteroids[j];
}
i -= 2;
size--;
}
if (size == 0) {
return new int[] {};
}
}
}
int[] result = new int[size];
System.arraycopy(asteroids, 0, result, 0, size);
return result;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(asteroidCollision(new int[]{1,-2,-2,-2})));
}
}
栈
import java.util.Arrays;
import java.util.Stack;
class Asteroids {
public static int[] asteroidCollision(int[] asteroids) {
Stack stack = new Stack<>();
int len = asteroids.length;//还是抽出来吧
for (int i = 0; i < len; i++){
if(asteroids[i] > 0){
stack.push(asteroids[i]);
}else if(asteroids[i] < 0){
if(stack.isEmpty() || stack.peek() < 0){ // peek前要判空的
stack.push(asteroids[i]);
continue;
}
boolean isEquals = false;//相等的情况,边界条件
if(Math.abs(asteroids[i]) > Math.abs(stack.peek())){
while(!stack.isEmpty() && stack.peek() > 0){
int ele = stack.peek();
if(Math.abs(ele) < Math.abs(asteroids[i])){
stack.pop();
}else if(Math.abs(ele) == Math.abs(asteroids[i])) { //相等的情况一定要考虑到
stack.pop();
isEquals = true;
break;
}else{
break;
}
}
if(isEquals == true){
isEquals = false;
continue;
}
if( stack.isEmpty() || stack.peek() < 0){ //注意条件的先后顺序
stack.push(asteroids[i]);
}
}else if(Math.abs(asteroids[i]) < Math.abs(stack.peek())){
continue;
}else {
stack.pop();
}
}else {
System.out.println("测试用例含有0");
}
}
int[] ans = new int[stack.size()];
for (int t = ans.length - 1; t >= 0; --t) {
ans[t] = stack.pop();
}
return ans;
}
public static void main(String[] args) {
//1,-2,-2,-2
//-2,-1,1,2
System.out.println(Arrays.toString(asteroidCollision(new int[]{-2,2,1,-2})));
}
}



