[JAVA 문제 풀이] 124. 배열 만들기 4

프로그래머스 (181918)
Stupefyee's avatar
Mar 06, 2025
[JAVA 문제 풀이] 124. 배열 만들기 4
notion image
 

내가 작성한 코드

import java.util.*; class Solution { public int[] solution(int[] arr) { List<Integer> stk = new ArrayList<>(); int i = 0; while (i < arr.length) { if (stk.isEmpty() || stk.get(stk.size()-1) < arr[i]) { stk.add(arr[i]); i++; continue; } if(stk.get(stk.size()-1) >= arr[i]) { stk.remove(stk.size()-1); continue; } } return stk.stream().mapToInt(p -> p).toArray(); } }
 

다른 사람의 코드

import java.util.Stack; class Solution { public int[] solution(int[] arr) { Stack<Integer> stack = new Stack<>(); for (int num : arr) { // 배열의 모든 요소 반복 // 스택이 비어있지 않고, 현재 요소(num)가 스택의 최상단 값보다 작거나 같다면 pop while (!stack.isEmpty() && num <= stack.peek()) stack.pop(); // 스택에 현재 요소 추가 stack.push(num); } // 스택을 배열로 변환하여 반환 return stack.stream().mapToInt(i -> i).toArray(); } }
 
Share article

stupefyee