leetcode134
class Solution {
public:
inline int get_next(int idx, int size)
{
return idx == size- ? : idx+;
}
int aux(int idx, vector<int>& gas, vector<int>& cost)
{
int i = idx;
int left = gas[i] - cost[i];
if(left < )
return -;
i = get_next(i, gas.size());
while( i!= idx)
{
left = left + gas[i] - cost[i];
if(left < )
return -;
i = get_next(i, gas.size());
}
return idx;
}
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int ret;
int i = ;
for(; i<gas.size(); ++i)
{
if(gas[i] >= cost[i])
{
ret = aux(i, gas, cost);
cout << ret << endl;
if(ret == -)
continue;
else
break;
}
}
return ret;
}
};
补充一个python的实现:
class Solution:
def canCompleteCircuit(self, gas: 'List[int]', cost: 'List[int]') -> int:
n = len(gas)
total =
sums =
begin =
for i in range(n):
diff = gas[i] - cost[i]
total += diff
sums += diff
if sums < :
begin = i +
sums =
if total < :
return -
return begin
题目确保,如果存在解,是唯一的解,因此程序只需要找出可以完成全程的第一个起点就行。
因为全程的加油数量和耗油数量都是固定的,因此从哪个点计算全程的总的消耗都是一样的。不需要先找到起点,然后再进行计算。
因此可以在一次循环中,完成两种计算:1判断是否可以走完全程(total是否小于0),2寻找第一个可以作为起点的坐标(begin)。
leetcode134的更多相关文章
- [Swift]LeetCode134. 加油站 | Gas Station
There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You ...
- LeetCode134:Gas Station
题目: There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. ...
- leetcode134 Gas Station
思路: https://leetcode.com/problems/gas-station/discuss/269604/Java-Greedy-thought-process 关键是要想清楚如果从加 ...
- Leetcode134. Gas Station加油站
在一条环路上有 N 个加油站,其中第 i 个加油站有汽油 gas[i] 升. 你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升.你从其中的一个加 ...
- leetcode134:3sum
题目描述 给出一个有n个元素的数组S,S中是否有元素a,b,c满足a+b+c=0?找出数组S中所有满足条件的三元组. 注意: 三元组(a.b.c)中的元素必须按非降序排列.(即a≤b≤c) 解集中不能 ...
随机推荐
- java BeanUtils.copyProperties
github搜索关键词: copyPropertiesIgnore https://github.com/longyi97/GA/blob/997e9c3a467268041c186234d91c4e ...
- shell 命令学习
https://blog.csdn.net/mnmlist/article/details/55215158
- ssh 免 密码登录另一台机器 和 secureCRT的乱码问题
PS: 就是你把密钥生成好以后,放入B机器中,再登录的时候就已经有了所以就不用验证了 ========================================================= ...
- day43 数据库知识欠缺的
一 什么是存储引擎 mysql中建立的库===>文件夹 库中建立的表===>文件 现实生活中我们用来存储数据的文件有不同的类型,每种文件类型对应各自不同的处理机制:比如处理文本用txt类型 ...
- 整理开源协议问题 GPL APACHE
整理开源协议问题 GPL APACHE APACHE 和 GPL 互相不兼容. APACHE 不可以使用 GPL 的代码. 但是 APACHE 可以调用 GPL 组件的接口. 比如 Linux 和 A ...
- 自适应巡航控制系统——ACC
ACC(Adaptive Cruise Control)自适应巡航控制系统(以下简称ACC)是一种基于传感器识别技术而诞生的智能巡航控制,相比只能根据驾驶者设置的速度进行恒定速度巡航的传统巡航控制系统 ...
- opencv mat flags含义
f:\opencv\opencv\sources\modules\core\src\matrix.cpp: flags = (_type & CV_MAT_TYPE_MASK) | MAGI ...
- gitlab-ce-omnibus社区版的备份、还原及升级
gitlab-ce-omnibus社区版的备份和还原,可以使用gitlab自带工具,gitlab-rake来完成,详见下面例子 将旧gitlab服务器备份,并还原至新gitlab服务器 ,这两台git ...
- bzoj 3674 可持久化并查集加强版——可持久化并查集
题目:https://www.lydsy.com/JudgeOnline/problem.php?id=3674 用主席树维护 fa[ ] 和 siz[ ] .改 fa[ ] 和改 siz[ ] 都 ...
- 学hadoop需要什么基础
最近一段时间一直在接触关于hadoop方面的内容,从刚接触时的一片空白,到现在也能够说清楚一些问题.这中间到底经历过什么只怕也就是只有经过的人才会体会到吧.前几天看到有个人问“学hadoop需要什么基 ...