https://leetcode.com/problems/distance-between-bus-stops/description/
Distance Between Bus Stops - LeetCode
Can you solve this real interview question? Distance Between Bus Stops - A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number
leetcode.com
간단 구현 문제였습니다.
📕 풀이방법
📔 입력 및 초기화
📔 풀이과정
distance의 모든 원소를 순회하며 전체 cost를 total에 저장합니다.
길의 모양은 위에서 봤을 때 사각형 형태를 띄며 대각선으로 가는 길이 없으므로 출발지에서 도착지까지 가는 방법에는 두 가지 길이 있습니다.
1. start -> destination
2. start뒤로 출발해 destination으로 돌고 돌아 도착
길이 양방향이므로 start와 destination중 작은 값에서 큰 값으로 distance를 더해주게되면 이것이 1번 길의 cost입니다.
이를 direct에 저장해줍니다.
이렇게 되면 total - direct가 2번 길에 해당하는 값입니다.
📔 정답 출력 | 반환
total - direct와 direct중 최솟값을 반환합니다.
📕 Code
📔 C++
class Solution {
public:
int distanceBetweenBusStops(vector<int>& distance, int start, int destination) {
int direct = 0, total = 0;
int sz = distance.size();
int st = min(start, destination);
int en = max(start, destination);
for(int i = 0; i < sz; i++) {
total += distance[i];
}
for(int i = st; i < en; i++) {
direct += distance[i];
}
return min(direct, total - direct);
}
};
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > Implementation' 카테고리의 다른 글
(C++) - LeetCode (easy) 1200. Minimum Absolute Difference (0) | 2023.12.04 |
---|---|
(C++) - LeetCode (easy) 1189. Maximum Number of Balloons (1) | 2023.11.29 |
(C++) - LeetCode (easy) 1175. Prime Arrangements (2) | 2023.11.20 |
(C++) - LeetCode (easy) 1154. Day of the Year (0) | 2023.11.14 |
(C++) - LeetCode (easy) 1103. Distribute Candies to People (0) | 2023.10.30 |