GuilinDev

Lc0735

05 August 2008

735 Asteroid Collision

一维数组正负数碰撞后剩下的,都为正或都为负

Stack

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
    public int[] asteroidCollision(int[] asteroids) {
        Stack<Integer> s = new Stack<>();
        int p = 0;
        while (p < asteroids.length) {
            if (s.empty() || s.peek() < 0 || asteroids[p] > 0) {
                s.push(asteroids[p]);
            } else if (s.peek() <= -asteroids[p]) {
                if (s.pop() < -asteroids[p]) {
                    continue;
                }
            }
            p++;
        }
        int[] ret = new int[s.size()];
        for (int i = ret.length - 1; i >= 0; i--) {
            ret[i] = s.pop();
        }
        return ret;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
    public int[] asteroidCollision(int[] asteroids) {
        if(asteroids == null || asteroids.length == 1){
            return new int[]{};
        }
        Deque<Integer> stack = new LinkedList<>();
        for(int a : asteroids){
            if(a > 0){ //feel free to push!
                stack.offerFirst(a);
            }else{
                while(!stack.isEmpty() && stack.peek() > 0 && -a > stack.peekFirst()){
                    stack.pollFirst();
                }
                //when we leave while loop, we have three cases:
                //1. the stack is empty
                if(stack.isEmpty()){
                    stack.offerFirst(a);
                }else{
                //2.1 stack.peekFiest is also negative  
                    if(stack.peekFirst() < 0){
                        stack.offerFirst(a);
                //2.2 stack.peekFirst wins the collision or a trie
                    }else if(stack.peekFirst() == -a){ 
                        stack.pollFirst();
                    }
                }
            }
        }
        int[] res = new int[stack.size()];
        for(int i = res.length - 1; i >= 0; i--){
            res[i] = stack.pollFirst();
        }
        return res;
    }
}