刚开始很迷惑,后来想到了栈来存储数据,关键是在左边数据大于零,右边数据小于零进行处理,
分三种情况讨论。
java版本:
class Solution {
public int[] asteroidCollision(int[] asteroids) {
// 栈也可以
ArrayDeque<Integer> stack=new ArrayDeque<>();
stack.offerFirst(asteroids[0]);
for(int i=1;i<asteroids.length;i++){
int left=stack.peek()==null ? 0:stack.peek();
stack.offerFirst(asteroids[i]);
while(!stack.isEmpty() && left>0 && asteroids[i]<0 ){
if(left>-asteroids[i]){
stack.poll();
break;
}else{
if(left==-asteroids[i]){
stack.poll();
stack.poll();
break;
}
if(left<-asteroids[i]){
stack.poll();
stack.poll();
left=stack.peekFirst()==null ? 0 : stack.peekFirst();
stack.push(asteroids[i]);
}
}
}
}
int[] res=new int[stack.size()];
int i=0;
while(!stack.isEmpty()){
res[i]=stack.pollLast();
i++;
}
return res;
}
}











网友评论