LeetCode-1184.公交站间的距离

题目:
LeetCode-1184.公交站间的距离_第1张图片
代码:

class Solution {
     
public:
    int distanceBetweenBusStops(vector<int>& distance, int start, int destination) {
     
        if(start==destination) return 0;
        int all=distance[0];
        for(int i=1;i<distance.size();i++) {
     
            all+=distance[i];
            distance[i]+=distance[i-1];
        }
        int ans;
        if(start==0) ans=distance[destination-1];
        else if(destination==0) ans=distance[start-1];
        else ans=distance[destination-1]-distance[start-1];
        if(ans<0) ans=-ans;
        if(2*ans>all) ans=all-ans;
        return ans;
    }
};

你可能感兴趣的:(LeetCode-1184.公交站间的距离)