Java, using stack


  • 1
    L
    class Solution {
    	public int[] asteroidCollision(int[] asteroids) {
    		ArrayList < Integer > res = new ArrayList < > ();
    		Stack < Integer > s = new Stack();
    		for (int i = 0; i < asteroids.length; i++) {
    			if (asteroids[i] > 0) {
    				s.push(asteroids[i]);
    			} 
    
    			while ((!s.isEmpty()) && (s.peek() < -(asteroids[i]))) {
    				s.pop();
    			}
    
    			if (((!s.isEmpty()) && (s.peek() > Math.abs(asteroids[i])))) {
    				continue;
    			} 
    
    			if ((!s.isEmpty()) && (asteroids[i] + s.peek() == 0)) {
    				s.pop();
    				continue;
    			}
    
    			if (asteroids[i] < 0) {
    				res.add(asteroids[i]);
    			}
    		}
    
    		res.addAll(s);
    		int[] result = new int[res.size()];
    
    		for (int j = 0; j < res.size(); j++) {
    			result[j] = res.get(j);
    		}
    		return result;
    	}
    }
    

  • 0

    @leetcode0705 said in Java, using stack:

    if (asteroids[i] > 0) {
        s.push(asteroids[i]);
    }
    
    else if (asteroids[i] < 0) {
        res.add(asteroids[i]);
    }
    

    Just have one question. In the first highlighted part, I get that you only want to add positive things into the stack. What is your logic in the second highlighted part? Under what condition you add negative elements into the stack? And one is add to the stack, the other is add to the List. Thanks!


  • 0
    L

    it's like, for instance, you have a negative number with large absolute value, like -800. It beats all the positive ones before it, like 2,3,4,5. It will remain, won't explode. But since it is negative, it won't be added to the result, so you'll have to use

    res.add(asteroids[i]);
    

    to add it to the result.
    :D


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.