본문 바로가기

공부/예제 풀이

[프로그래머스] 뒤에있는 큰 수 찾기

//100만개의 원소를 for문을 돌면서 탐색하는건 무조건 시간초과임
//sort도 못함 각 인자의 순서로 해야함.
//최악의 경우가 맨 마지막에 가장 큰수가 있을 경우 100만개의 행을 다 비교하면서 돌아야됨
//적합한 자료구조가 있나..? 큐? 
//어떻게 쓸건데? 큐는 못씀 중간에 껴있는 값들을 비교해야 하는데 그걸 못하니까
//완전 탐색? 그건 필요 없을거 같은데 for문과 다르지 않잖아
//스택 : 원소들을 쌓고 새로 들어온 값이 마지막 원소보다 커? 팝(새로운 원소값으로) 다시 비교해서 커? 팝
//새로운 원소는 다시 스택에 넣고 
//그럼 이걸 인덱스 관리를 어떻게 할건데?? 팝할 때 그 인덱스는 어떻게 알지??
//아 인덱스를 넣어준다? 스택에다가???
//스택에 인덱스를 넣어줘
//비교할 땐 인덱스의 numbers[index]를 이용해서 비교해
// 비교해서 크면? 팝 하고 그 인덱스를 엔서에 넣어주고


import java.util.*;

class Solution {
    public int[] solution(int[] numbers) {
        int[] answer = new int[numbers.length];
        Stack<Integer> stack = new Stack<>();
        stack.push(0);
        for(int i=1;i<numbers.length;i++){
            while(!stack.isEmpty()){
               if(numbers[stack.peek()]<numbers[i]){
                    answer[stack.pop()] = numbers[i];
                }else{
                    break;
                }
            }
            stack.push(i);
        }
        while(!stack.isEmpty()){
            answer[stack.pop()] = -1;
        }
        return answer;
    }
}