leetcode--1184.公交站间的距离

问题描述:
在这里插入图片描述
示例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。

思路:

最开始我是想着将起点start和终点destination顺时针的长度和逆时针的长度都记录下来,将两个值进行对比,取最小值。但是我发现"逆时针"的时候并不好去记录长度。然后我突然意识到:只需要记录较为方便计数的方向的长度,用最后的总长度将其一减就是另一个方向的路径的长度。所以就是用总长度sum减去从start到destination的长度和sum1就是另一条的长度sum2。

java代码

class Solution {
    public int distanceBetweenBusStops(int[] distance, int start, int destination) {
        int count1=0;
        int count2=0;
        int sum=0;
        int min=Math.min(start,destination);
        int max=Math.max(start,destination);
         for(int i=0;i<distance.length;i++){
            sum+=distance[i];
        }
        for(int j=min;j<max;j++){
            count1+=distance[j];
        }
        count2=sum-count1;
        int shortpath = Math.min(count1,count2);
        return shortpath;
    }
}

在这里插入图片描述

发布了73 篇原创文章 · 获赞 7 · 访问量 3567

猜你喜欢

转载自blog.csdn.net/weixin_43801718/article/details/103481229
今日推荐