TIL

[코테연습] 2037. Minimum Number of Moves to Seat Everyone

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

- 배열 정렬 문제

 

https://leetcode.com/problems/minimum-number-of-moves-to-seat-everyone/description/?envType=daily-question&envId=2024-06-13

 

- 문제분석

1. int[] seats 배열과 int[] students[] 배열이 있다.

2. seats 배열의 각 원소는 좌석의 번호이다.

3. students 의 배열은 각 학생의 번호이다.

4. 좌석번호와 각 학생번호가 같도록 가장 최소한의 움직임을 구하여 리턴하여라.

 

- 문제풀이

1. seats 배열과 students 배열을 Arrays.sort() 함수로 정렬한다.

2. 반복문을 통해 각 원소의 차이를 Math.abs 로 구한다.

3. 원소의 차이를 더하여 리턴한다.

 

class Solution {
    public int minMovesToSeat(int[] seats, int[] students) {
        Arrays.sort(seats);
        Arrays.sort(students);

        int cnt = 0;
        for(int i = 0; i < students.length; i++) {
            int st = students[i];
            int seat = seats[i];
            int diff = 0;
            if (seat != st) {
                diff = Math.abs(seat-st);
            }
            cnt+=diff;
        }
        return cnt;
    }
}