프로그래머스
프로그래머스 - 탑
thiago6
2019. 1. 12. 16:25
내 코드
class Solution {
public int[] solution(int[] heights) {
int[] answer = new int[heights.length];
outer:
for (int i = 1; i < heights.length; i++) {
for (int j = i - 1; j > -1; j--) {
if (heights[i] < heights[j]) {
answer[i] = j + 1;
continue outer;
} else {
answer[i] = 0;
}
}
}
return answer;
}
}
문제 분류가 스택, 큐라서 바꿔 본 코드
이 문제에서는 스택을 쓰는게 딱히 의미는 없을 것 같다.
배운 점 : stack.size()를 기준으로 반복문을 돌리면 안된다. --> 계속 변함
import java.util.*;
class Solution {
public int[] solution(int[] heights) {
int[] answer = new int[heights.length];
Stack<Integer> stack = new Stack<>();
for (int height: heights) {
stack.push(height);
}
int next;
int i = 0;
while(!stack.empty()) {
next = stack.pop();
for (int j = stack.size() - 1; j > -1; j--) {
if (next < heights[j]) {
answer[heights.length - i - 1] = j + 1;
break;
}
}
i++;
}
return answer;
}
}