Created
February 13, 2024 07:04
-
-
Save ritik-agrawal/0f00f1feaca2f754a669772f2ea750c8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public int[] asteroidCollision(int[] asteroids) { | |
var len = asteroids.length; | |
var stk = new ArrayList<Integer>(); | |
for (int cur : asteroids){ | |
if (Objects.nonNull(peek(stk)) && isPositiveNegative(peek(stk), cur)){ | |
if ((peek(stk) + cur) == 0){ | |
pop(stk); | |
} else if ((peek(stk) + cur) < 0){ | |
while( | |
(Objects.nonNull(peek(stk))) && (isPositiveNegative(peek(stk), cur)) && | |
((peek(stk) + cur) < 0) | |
){ | |
pop(stk); | |
} | |
if (Objects.nonNull(peek(stk)) && isPositiveNegative(peek(stk), cur) && (peek(stk) + cur) == 0){ | |
pop(stk); | |
} else if (Objects.isNull(peek(stk)) || !isPositiveNegative(peek(stk), cur)){ | |
stk.add(cur); | |
} | |
} | |
} else { | |
stk.add(cur); | |
} | |
} | |
return toArray(stk); | |
} | |
private Integer peek(List<Integer> stk){ | |
Integer retVal = null; | |
if (stk.size() != 0){ | |
retVal = stk.get(stk.size() - 1); | |
} | |
return retVal; | |
} | |
private void pop(List<Integer> stk){ | |
if (stk.size() != 0){ | |
stk.remove(stk.size() - 1); | |
} | |
} | |
private int[] toArray(List<Integer> stk){ | |
var retVal = new int[stk.size()]; | |
for (int i = 0; i < stk.size(); i++){ | |
retVal[i] = stk.get(i); | |
} | |
return retVal; | |
} | |
private boolean isPositiveNegative(Integer top, Integer cur){ | |
if (Objects.nonNull(top)){ | |
return ( | |
(top > 0) && (cur < 0) | |
); | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yet Another Better Solution
The below solution also is done by manipulating the array.