본문 바로가기

프로그래머스

프로그래머스 - 탑

내 코드

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;
}
}


'프로그래머스' 카테고리의 다른 글

프로그래머스 - 전화번호 목록  (0) 2019.01.13
프로그래머스 - 124 나라의 숫자  (0) 2019.01.13
프로그래머스 - 체육복  (0) 2019.01.10
프로그래머스 - 예산  (0) 2019.01.10
프로그래머스 - 2016년  (0) 2019.01.10