-
Notifications
You must be signed in to change notification settings - Fork 0
/
Asteroid_Collision.java
72 lines (70 loc) · 2.38 KB
/
Asteroid_Collision.java
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.leet_code;
import java.util.Arrays;
import java.util.Stack;
public class Asteroid_Collision {
public static void main(String[] args) {
int[] arr={8,-8};
System.out.println(Arrays.toString(asteroidCollision(arr)));
}
public static int[] asteroidCollision(int[] ast) {//is not working well
Stack<Integer> srr=new Stack<>();
srr.push(ast[0]);
for (int i = 1; i < ast.length; i++) {
if (ast[i] < 0 && srr.peek()>=0) {//collide condition
if(Math.abs(srr.peek()) == Math.abs(ast[i])){
srr.pop();
}
if (Math.abs(srr.peek()) > Math.abs(ast[i])) {
srr.push(ast[i]);
}else {// 10 -11
while(Math.abs(srr.peek()) < Math.abs(ast[i]) && srr.peek()>0 && ast[i]<0) {
srr.pop();
}
srr.push(ast[i]);
}
}else {
srr.push(ast[i]);
}
}
int[] arr=new int[srr.size()];
for (int i = 0; i < srr.size(); i++) {
arr[i]=srr.get(i);
}
return arr;
}
public int[] asteroidCollision1(int[] asteroids) {// online chapa
int[] stack = new int[asteroids.length];
int top = -1;
for (int g : asteroids) {
if (top == -1) {
stack[++top] = g;
} else {
if (g < 0) {
if (stack[top] < 0) {
stack[++top] = g;
} else {
while (top >= 0 && stack[top] > 0 && stack[top] < (-g)) {
top--;
}
if (top >= 0) {
if (stack[top] > 0 && stack[top] == (-g)) {
top--;
} else if (stack[top] < 0) {
stack[++top] = g;
}
} else {
stack[++top] = g;
}
}
} else {
stack[++top] = g;
}
}
}
int[] ans = new int[top + 1];
for (int i = 0; i <= top; i++) {
ans[i] = stack[i];
}
return ans;
}
}