🎈 算法并不一定都是很難的題目,也有很多只是一些代碼技巧,多進行一些算法題目的練習,可以幫助我們開闊解題思路,提升我們的邏輯思維能力,也可以將一些算法思維結合到業務代碼的編寫思考中。簡而言之,平時進行的算法習題練習帶給我們的好處一定是不少的,所以讓我們一起來養成算法練習的習慣。今天練習的題目是一道比較簡單的題目 ->公交站間的距離
問題描述
環形公交路線上有 n
個站,按次序從 0
到 n - 1
進行編號。我們已知每一對相鄰公交站之間的距離,distance[i]
表示編號為 i
的車站和編號為 (i + 1) % n
的車站之間的距離。
環線上的公交車都可以按順時針和逆時針的方向行駛。
返回乘客從出發點 start
到目的地 destination
之間的最短距離。
示例 1:
輸入: distance = [1,2,3,4], start = 0, destination = 1
輸出: 1
解釋: 公交站 0 和 1 之間的距離是 1 或 9,最小值是 1。
示例 2:
輸入: distance = [1,2,3,4], start = 0, destination = 2
輸出: 3
解釋: 公交站 0 和 2 之間的距離是 3 或 7,最小值是 3。
示例 3:
輸入: distance = [1,2,3,4], start = 0, destination = 3
輸出: 4
解釋: 公交站 0 和 3 之間的距離是 6 或 4,最小值是 4。
提示:
1 <= n <= 10^4
distance.length == n
0 <= start, destination < n
0 <= distance[i] <= 10^4
思路分析
首先我們要先理解一下題目的意思,公交路線為一個環形,題目會給我們一個數組distance
,每一對相鄰公交站之間的距離,distance[i]
表示編號為 i
的車站和編號為 (i + 1) % n
的車站之間的距離。因為公交路線為一個環形,所以我們只能按照順時針或逆時針方向駛向相鄰的公交車站,也就是說編號為i
的公交站只能駛向編號為(i + 1) % n
或 (i - 1 + n) % n
。所以從start
駛向destination
只有兩條路線,我們只需要分別算出兩條路線的行駛距離,取較小的即可。
- 1、先算環形路線總距離
我們可以使用reduce
方法來快速求出數組的和:
const sum = distance.reduce((a, b) => a + b);
- 2、順時針從
start
駛向destination
的距離
首先我們可以先保證start
小于 destination
:if (start > destination) [start, destination] = [destination, start];
,然后遍歷對start
和destination
之間的數據進行求和即可:
if (start > destination) [start, destination] = [destination, start];
let res = 0;
while (start < destination) {res += distance[start++];
}
- 3、計算逆時針方向路線距離并取其較小值
前面我們已經計算出環形路線的總和了,所以我們可以直接使用總和減去當前路線的距離,即可得出另一路線的距離:
return Math.min(res, sum - res);
AC代碼
完整AC代碼如下:
/*** @param {number[]} distance* @param {number} start* @param {number} destination* @return {number}*/
var distanceBetweenBusStops = function (distance, start, destination) {const sum = distance.reduce((a, b) => a + b);if (start > destination) [start, destination] = [destination, start];let res = 0;while (start < destination) {res += distance[start++];}return Math.min(res, sum - res);
};
當然,我們也可以通過一次遍歷的方法來直接得出答案:
var distanceBetweenBusStops = function (distance, start, destination) {if (start > destination) [start, destination] = [destination, start];let sum1 = 0,sum2 = 0;distance.forEach((item, index) => {if (index >= start && index < destination) sum1 += item;else sum2 += item;});return Math.min(sum1, sum2);
};
公眾號
關注公眾號『前端也能這么有趣
』,獲取更多有趣內容。
說在后面
🎉 這里是 JYeontu,現在是一名前端工程師,有空會刷刷算法題,平時喜歡打羽毛球 🏸 ,平時也喜歡寫些東西,既為自己記錄 📋,也希望可以對大家有那么一丟丟的幫助,寫的不好望多多諒解 🙇,寫錯的地方望指出,定會認真改進 😊,偶爾也會在自己的公眾號『
前端也能這么有趣
』發一些比較有趣的文章,有興趣的也可以關注下。在此謝謝大家的支持,我們下文再見 🙌。