코딩테스트 풀이/JAVA
[LeetCode/Easy] 1184. Distance Between Bus Stops
무지맘
2023. 4. 5. 22:45
1. Input
1) int[] distance
- n == distance.length
2) int start
3) int destination
2. Output
1) start에서 destination까지 가는 최단 경로를 반환
- 버스정류장은 0번부터 n-1번까지 있다.
- 시계방향으로 가거나 반시계방향으로 갈 수 있다.
- distance[i] == i번 버스정류장과 (i+1)%n번 버스정류장 사이의 거리
3. Constraint
1) 1 <= n <= 10^4
2) 0 <= start, destination < n
3) 0 <= distance[i] <= 10^4
4. Example
Input: distance = [1,2,3,4], start = 0, destination = 2 -> Output: 3
설명:
- 시계방향: 1 + 2 = 3
- 반시계방향: 4 + 3 = 7
- 따라서 3을 반환한다.
5. Code
1) 첫 코드(2023/04/05)
int total = 0, sum = 0, a = Math.min(start,destination), b = Math.max(start,destination);
for(int i=0 ; i<distance.length ; i++){
total += distance[i];
if(a<=i && i<b)
sum += distance[i];
}
return Math.min(total-sum, sum);
- 오랜만에 괜찮은 성능이 나왔다.