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-12-24怎么切换 Git 项目的远程仓库地址?-icode9专业技术文章分享
- 2024-12-24怎么更改 Git 远程仓库的名称?-icode9专业技术文章分享
- 2024-12-24更改 Git 本地分支关联的远程分支是什么命令?-icode9专业技术文章分享
- 2024-12-24uniapp 连接之后会被立马断开是什么原因?-icode9专业技术文章分享
- 2024-12-24cdn 路径可以指定规则映射吗?-icode9专业技术文章分享
- 2024-12-24CAP:Serverless?+AI?让应用开发更简单
- 2024-12-23新能源车企如何通过CRM工具优化客户关系管理,增强客户忠诚度与品牌影响力
- 2024-12-23原创tauri2.1+vite6.0+rust+arco客户端os平台系统|tauri2+rust桌面os管理
- 2024-12-23DevExpress 怎么实现右键菜单(Context Menu)显示中文?-icode9专业技术文章分享
- 2024-12-22怎么通过控制台去看我的页面渲染的内容在哪个文件中呢-icode9专业技术文章分享