728x90
반응형
문제
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
코드
1. 2중 for문을 이용한 풀이
class Solution {
public int[] solution(int[] prices) {
int N = prices.length;
int[] ans = new int[N];
for (int i = 0; i < N; i ++) {
for (int j = i + 1; j < N; j ++) {
// 감소가 이루어지지 않을때까지 ++
ans[i] ++;
// 감소가 이루어지면 break
if (prices[i] > prices[j]) break;
}
}
return ans;
}
}
2. stack 자료구조를 이용한 풀이
import java.util.*;
class Solution {
public int[] solution(int[] arr) {
int N = arr.length;
int[] ans = new int[N];
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < N; i ++) {
// 감소하는 상황
while(!stack.isEmpty() && arr[stack.peek()] > arr[i]){
ans[stack.peek()] = i - stack.peek();
stack.pop();
}
stack.push(i);
}
while(!stack.isEmpty()){
int tmp = stack.peek();
ans[tmp] = N - 1 - tmp;
stack.pop();
}
return ans;
}
}
728x90
반응형