题解 | #加油站#

加油站

http://www.nowcoder.com/practice/a013a0691a0343aeb262ca1450d2fe4e

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param gas int整型vector 
     * @param cost int整型vector 
     * @return int整型
     */
    // 贪心法
    int gasStation(vector<int>& gas, vector<int>& cost) {
        int n = gas.size();
        int res = 0, sum = 0, start = 0;
        
        for(int i=0; i<n; i++){
            res += gas[i] - cost[i];
            sum += gas[i] - cost[i];
            if(res < 0){
                start = (i+1)%n;
                res = 0;
            }
        }
        
        return sum >= 0 ? start : -1;
    }
    /*
    // 遍历所有起始点
    int gasStation(vector<int>& gas, vector<int>& cost) {
        // write code here
        int n = gas.size();
        int res;
        for(int i=0; i<n; i++){
            int cur = 0;
            res = gas[i];
            int start = i;
            while(res > 0){
                res = res - cost[(start % n)];
                if(res < 0){
                    break;
                }
                cur += 1;
                res += gas[(start + 1)%n];
                if(cur == n){
                    return i;
                }
                start += 1;
            }
        }
        
        return -1;
    }
    */
};
全部评论

相关推荐

在debug的柠檬精很迷人:好消息:现在HR挑三拣四 15年后 HR跪着求要简历 坏消息:被挑的是这代人,到时候求人的也是这代人。真好。
点赞 评论 收藏
分享
嵌入式求职之路:可以看我经验😂,https://www.nowcoder.com/share/jump/73221730841876945
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务