잡다로그

[99클럽 코테 스터디] 14일차 TIL - 그래프, Minimum Number of Moves to Seat Everyone 본문

Algorithm

[99클럽 코테 스터디] 14일차 TIL - 그래프, Minimum Number of Moves to Seat Everyone

날으는다람쥐 2024. 6. 13. 21:39

[14일차] 그래프

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

* 대충 번역: 한 방에 n명의 학생들이 n개의 의자에 앉아있다. 길이가 n인 seats라는 배열이 주어진다. seats[i]는 i번째 자리의 위치를 의미한다. 길이 n인 students 배열도 주어진다. students[j]는 j번째 학생의 위치를 의미한다.

다음과 같은 이동을 할 수 있다. i번째 학생의 위치를 ​​1만큼 증가 또는 감소시킨다 (즉, i번째 학생을 위치 x에서 x + 1 또는 x - 1로 이동).

모든 학생이 서로 다른 자리에 앉도록 이동하는 데 필요한 최소 이동 횟수를 반환하라. 초기에는 동일한 위치에 여러 좌석이나 학생이 있을 수 있습니다.

Solution

students 배열과 seats배열의 최소 차이(덧셈 혹은 뺄셈으로)를 구해야 한다.

class Solution(object):
    def minMovesToSeat(self, seats, students):
        """
        :type seats: List[int]
        :type students: List[int]
        :rtype: int
        """
        
        seats.sort()
        students.sort()

        result = 0

        for i in range(len(students)):
            result += abs(seats[i] - students[i])

        return result

나다어

  • 절댓값 라이브러리는 abs() 이다.
  • 두 배열이 같은 인덱스를 공유할 때, zip() 을 사용할 수도 있다.
for se,st in zip(seats, students):
    result += abs(se - st)
Comments