[LeetCode] Distance Between Bus Stops

아르당·2026년 4월 7일

LeetCode

목록 보기
248/261
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

버스는 0부터 n - 1까지 번호가 매겨진 n개의 정류장을 순환한다. 인접한 모든 정류장 사이의 거리는 distance[i]와 (i + 1) % n이라는 것을 알고 있다.

버스는 시계 방향과 반시계 방향 모두 운행한다.

주어진 start와 destination 사이의 최단 거리를 반환해라.

Example

#1

Input: distance = [1, 2, 3, 4], start = 0, destination = 1
Output: 1
Explanation: 0과 1사이의 거리는 1이나 9이고, 최소값은 1이다.

#2

Input: distance = [1, 2, 3, 4], start = 0, destination = 2
Output: 3
Explanation: 0과 2사이의 거리는 3이나 7이고, 최소값은 3이다.

#3

Input: distance = [1, 2, 3, 4], start = 0, destination = 3
Output: 4
Explanation: 0과 3사이의 거리는 6이나 4이고, 최소값은 4이다.

Constraints

  • 1 <= n <= 10^4
  • distance.length == n
  • 0 <= start, destination < n
  • 0 <= distance[i] <= 10^4

Solved

class Solution {
    public int distanceBetweenBusStops(int[] distance, int start, int destination) {
        int left = 0;
        int right = 0;

        if(start > destination){
            int temp = start;
            start = destination;
            destination = temp;
        }

        for(int i = start; i < destination; i++){
            left += distance[i];
        }

        for(int i = destination; i != start; i = (i + 1) % distance.length){
            right += distance[i];
        }

        return Math.min(left, right);
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글