美文网首页
2022-01-14 II 037. 小行星碰撞

2022-01-14 II 037. 小行星碰撞

作者: 16孙一凡通工 | 来源:发表于2022-01-14 11:10 被阅读0次

刚开始很迷惑,后来想到了栈来存储数据,关键是在左边数据大于零,右边数据小于零进行处理,
分三种情况讨论。
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;
             
          }
         

      }

相关文章

网友评论

      本文标题:2022-01-14 II 037. 小行星碰撞

      本文链接:https://www.haomeiwen.com/subject/xbdacrtx.html