当前位置:网站首页>Distance between bus stops: simple simulation problem

Distance between bus stops: simple simulation problem

2022-07-26 05:01:00 Fat technology house

Title Description

This is a LeetCode Upper 1184. The distance between bus stops , The difficulty is Simple .

Tag : 「 simulation 」

There are... On the circular bus route  nnn  Individual station , From  000  To  n−1n - 1n−1  Number . We know the distance between each pair of adjacent bus stops ,distance[i]distance[i]distance[i]  Indicates that the number is  iii  The station and number are  (i + 1) % n  The distance between the stations .

The buses on the loop line can travel clockwise and counterclockwise .

Return passengers from the starting point  start  Destination  destination  The shortest distance between .

Example 1:

 Input :distance = [1,2,3,4], start = 0, destination = 1

 Output :1

 explain : Bus stop  0  and  1  The distance between them is  1  or  9, The minimum is  1.
 Copy code 

Example 2:

 Input :distance = [1,2,3,4], start = 0, destination = 2

 Output :3

 explain : Bus stop  0  and  2  The distance between them is  3  or  7, The minimum is  3.
 Copy code 

Example 3:

 Input :distance = [1,2,3,4], start = 0, destination = 3

 Output :4

 explain : Bus stop  0  and  3  The distance between them is  6  or  4, The minimum is  4.
 Copy code 

Tips :

  • 1<=n <=1041 <= n <= 10^41<=n <=104
  • distance.length==ndistance.length == ndistance.length==n
  • 0<=start,destination<n0 <= start, destination < n0<=start,destination<n
  • 0<=distance[i]<=1040 <= distance[i] <= 10^40<=distance[i]<=104

simulation

Simulate according to the meaning of the question .

use i and j The pointer representing forward and backward respectively ,a and b Calculate the total cost of the two methods respectively .

Java Code :

class Solution {
    public int distanceBetweenBusStops(int[] dist, int s, int t) {
        int n = dist.length, i = s, j = s, a = 0, b = 0;
        while (i != t) {
            a += dist[i];
            if (++i == n) i = 0;
        }
        while (j != t) {
            if (--j < 0) j = n - 1; 
            b += dist[j];
        }
        return Math.min(a, b);
    }
}
 Copy code 

TypeScript Code :

function distanceBetweenBusStops(dist: number[], s: number, t: number): number {
    let n = dist.length, i = s, j = s, a = 0, b = 0
    while (i != t) {
        a += dist[i]
        if (++i == n) i = 0
    }
    while (j != t) {
        if (--j < 0) j = n - 1
        b += dist[j]
    }
    return Math.min(a, b)
};
 Copy code 
  • Time complexity :O(n)O(n)O(n)
  • Spatial complexity :O(1)O(1)O(1)


 

原网站

版权声明
本文为[Fat technology house]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/207/202207260458339063.html