문제 요약
🏙️ N개의 높이가 서로 다른 타워가 왼쪽→오른쪽 순서로 일직선 위에 서 있고,
🔫 각 타워에서 왼쪽 방향으로 레이저 신호를 발사한다.
🎯 이 신호는 가장 먼저 만나는 왼쪽 방향의 타워 하나만 수신 가능.
출력: 각 타워가 발사한 신호를 수신하는 타워 번호(없으면0
).
height[j] > height[i]
인 최초의 j 찾기 (인덱스, 높이)
저장 result[popIdx] = 현재인덱스 + 1
⚙️ 결과
0
int[] result = new int[N];
Stack<int[]> stack = new Stack<>();
// 1) 오른쪽 끝 → 왼쪽 순회
for (int i = N-1; i >= 0; i--) {
int curH = heights[i];
// 2) 더 높은 타워 등장 시 pop & 결과 기록
while (!stack.isEmpty() && curH > stack.peek()[1]) {
int[] top = stack.pop();
result[top[0]] = i + 1; // 📌 1-based index
}
// 3) 현재 타워도 후보로 push
stack.push(new int[]{i, curH});
}
// 4) 남은 타워들은 수신자 없음 → 기본값 0 유지
Stack<int[]>
(int[]{index, height}
) i+1
heights = [6, 9, 5, 7, 4]
i = 4 (4️⃣) → stack empty → push(4,4)
i = 3 (7️⃣)
→ 7 > 4? ✅ → pop(4) → result[4]=4
→ stack empty → push(3,7)
i = 2 (5️⃣)
→ 5 > 7? ❌ → push(2,5)
i = 1 (9️⃣)
→ 9 > 5? ✅ → pop(2) → result[2]=2
→ 9 > 7? ✅ → pop(3) → result[3]=2
→ stack empty → push(1,9)
i = 0 (6️⃣)
→ 6 > 9? ❌ → push(0,6)
최종 result = [0, 0, 2, 2, 4]
i+1
int[]{index, height}
→ pop 시 인덱스·높이를 동시에 사용