TIL

[코테연습] 2751. Robot Collisions

크라00 2024. 7. 13. 21:11

- 스택/큐 문제

 

https://leetcode.com/problems/robot-collisions/submissions/1319632434/?envType=daily-question&envId=2024-07-13

 

class Solution {
    public List<Integer> survivedRobotsHealths(int[] positions, int[] healths, String directions) {

        int n = positions.length;

        //Position index 별로 정리
        Integer[] array = new Integer[n];
        Stack<Integer> stack = new Stack<>();

        for(int i = 0 ; i < n; i++) {
            array[i] = i;
        }

        //positions 현재 정렬 방식을 반영하여 array 정렬.
        Arrays.sort(array, (o1, o2) -> Integer.compare(positions[o1], positions[o2]));

        for(int i = 0; i < n; i++) {
            int nowIndex = array[i];
            if (directions.charAt(nowIndex) == 'R') {
                stack.push(nowIndex); // 'R' 일때만 stack 에 맨처음 반영, L 의 경우 첫번째가 될 수 없다.
            } else {
                while(!stack.isEmpty() && healths[nowIndex] > 0) {

                    int index = stack.pop();//R 이 담겨져 있는 stack 의 index
                    
                    int r = healths[index];
                    int l = healths[nowIndex]; // L 일 경우에 반영됨.
                    //r 과 l 을 비교하여, health array 에 직접적으로 반영.
                    if (r > l) {
                        healths[index] -= 1;
                        healths[nowIndex] = 0; 
                        stack.push(index); // 더 많은 R 다시 넣기
                    //l 이 더 클 경우
                    } else if (r < l) {
                        healths[index] = 0;
                        healths[nowIndex] -= 1;
                    //r == l
                    } else {
                        healths[index] = 0;
                        healths[nowIndex] = 0;
                    }
                }
            }
        }

        List<Integer> rsList = new ArrayList<>();
        for(int i = 0 ; i < n; i++ ) {
            if (healths[i] > 0) {
                rsList.add(healths[i]);
            }
        }

        return rsList;
    }
}