134. Gas Station
来源:互联网 发布:显示登录成功和链接php 编辑:程序博客网 时间:2024/06/06 02:52
问题描述
There are N gas stations along a circular route, where the amount of gas at station i is gas[i].You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
Return the starting gas station’s index if you can travel around the circuit once, otherwise return -1.
Note:
The solution is guaranteed to be unique.解决思路
其实就是找到从哪个点开始遍历,和一直不为负数。这里有一个问题就是只能够正向走,即i 只能走向i+1。所以我们可以假定从最后一个节点开始走,如果和为正,就正向走,如果和为负数,则将开始节点倒退,一直倒退到和为正位置。则最后倒退到不能倒退的节点就是我们要找的目标节点,如果最后得和还是负数,则不存在这样的节点。代码
class Solution {public: int canCompleteCircuit(vector<int>& gas, vector<int>& cost) { int n = gas.size(); if (n == 1) { if (gas[0] >= cost[0]) return 0; else return -1; } int end = n - 1, start = 0; int sum = gas[end]-cost[end]; while(end > start) { if (sum > 0) { sum += gas[start]-cost[start]; ++start; } else { --end; sum += gas[end]-cost[end]; } } return sum >= 0 ? end:-1; }};
0 0
- [LeetCode]134.Gas Station
- LeetCode 134. Gas Station
- [Leetcode] 134. Gas Station
- 134. Gas Station
- [leetcode] 134. Gas Station
- Leetcode-134.Gas Station
- 134. Gas Station LeetCode
- 134. Gas Station
- Leetcode 134. Gas Station
- 134. Gas Station
- 134. Gas Station
- [LeetCode]134. Gas Station
- LeetCode 134. Gas Station
- leetcode 134. Gas Station
- LeetCode *** 134. Gas Station
- 134. Gas Station
- LeetCode 134. Gas Station
- 【LeetCode】134. Gas Station
- 安卓Android单表通用数据库、万能数据库的设计,(sqlite,java反射,泛型),使用非常方便
- 关于2017开始的新工作想法与一些学习进步方向还有些阶段目标
- 常用的线程池
- 编码(三):Java Web编码问题
- Android 内存泄漏之handler
- 134. Gas Station
- SLIC超像素分割算法研究(代码可下载)
- 史上最详细最全面的ss-panel部署教程(V3版本)
- nyoj 14 会场安排问题
- IO流文件的复制删除
- R语言常用函数总结大全
- 线线几何位置关系
- 三种常用排序算法(冒泡、选择、快速)的Java实现
- JQueryEasyUI 组件 布局 Layout组件