새소식

알고리즘/문제

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

  • -

문제 출처 : https://school.programmers.co.kr/learn/courses/30/lessons/154539

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


public class Programmers_뒤에있는큰수찾기 {
public static void main(String[] args) {
System.out.println(Arrays.toString(solution(new int[]{2, 3, 3, 5})));
System.out.println(Arrays.toString(solution(new int[]{9, 1, 5, 3, 6, 2})));
}
private static int[] solution(int[] arr){
int[] answer = new int[arr.length];
Stack<Integer> s = new Stack<>();
for(int i=arr.length-1; i>=0; i--){
while(!s.isEmpty()){
if(s.peek() > arr[i]){
answer[i] = s.peek();
break;
}else{
s.pop();
}
}
if(s.isEmpty()){
answer[i] = -1;
}
s.push(arr[i]);
}
return answer;
}
}

뒤에 있는 큰수를 찾기 위해 스택을 사용했다

 

스택을 peek으로 확인하여 값이

배열값 보다 크다면 answer에 담아주고

배열값 보다 작다면 pop을 하며 다음 원소를 검사한다

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.