LeetCode Gas Station 数学
2022/7/14 23:20:14
本文主要是介绍LeetCode Gas Station 数学,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
There are n
gas stations along a circular route, where the amount of gas
at the \(i\)th station is gas[i]
.
You have a car with an unlimited gas tank and it costs cost[i]
of gas to travel from the \(i\)th station to its next \((i + 1)\)th station. You begin the journey with an empty tank at one of the gas stations.
Given two integer arrays gas
and cost
, return the starting gas
station's index if you can travel around the circuit once in the clockwise direction, otherwise return \(-1\). If there exists a solution, it is guaranteed to be unique
Solution
给定一个圆环,有若干个加油站,问是否存在一个起始点使得空油箱的汽车跑完一周。不妨记:
\[dif[i] = gas[i]-cost[i] \]假设从 \(i\) 开始,此时到达 \(i+1\) 需要满足:
\[res[i+1] = gas[i]-cost[i]=dif[i]\geq 0 \]类似地,到达 \(i+2\) 需要满足:
\[dif[i]+dif[i+1]\geq 0 \]可以发现这就是前缀和,对于环形问题,我们可以摊开为一个 \(2n\) 的序列即可。所以只需要所有的前缀和非负即可
点击查看代码
class Solution { private: int dif[200005]; int ans = 0; public: int canCompleteCircuit(vector<int>& gas, vector<int>& cost) { int n = gas.size(); int ck = 0; for(int i=0;i<n;i++)dif[i] = gas[i]-cost[i], ck += dif[i]; for(int i=n;i<2*n;i++)dif[i] = dif[i-n]; int fg=0; if(ck<0)return -1; int tank_V = 0, st = 0; for(int i=0;i<2*n;i++){ tank_V += dif[i]; if(tank_V<0){ tank_V = 0; st = i+1; } } return st%n; } };
这篇关于LeetCode Gas Station 数学的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15PingCAP 黄东旭参与 CCF 秀湖会议,共探开源教育未来
- 2024-05-13PingCAP 戴涛:构建面向未来的金融核心系统
- 2024-05-09flutter3.x_macos桌面os实战
- 2024-05-09Rust中的并发性:Sync 和 Send Traits
- 2024-05-08使用Ollama和OpenWebUI在CPU上玩转Meta Llama3-8B
- 2024-05-08完工标准(DoD)与验收条件(AC)究竟有什么不同?
- 2024-05-084万 star 的 NocoDB 在 sealos 上一键起,轻松把数据库编程智能表格
- 2024-05-08Mac 版Stable Diffusion WebUI的安装
- 2024-05-08解锁CodeGeeX智能问答中3项独有的隐藏技能
- 2024-05-08RAG算法优化+新增代码仓库支持,CodeGeeX的@repo功能效果提升