news 2026/7/28 17:21:17

LeetCode gas-station

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
LeetCode gas-station

题目描述

环形路上有n个加油站,第i个加油站的汽油量是gas[i].

你有一辆车,车的油箱可以无限装汽油。从加油站i走到下一个加油站(i+1)花费的油量是cost[i],你从一个加油站出发,刚开始的时候油箱里面没有汽油。

求从哪个加油站出发可以在环形路上走一圈。返回加油站的下标,如果没有答案的话返回-1。

注意:

答案保证唯一。

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.

解题思路

从start出发,油量够就一直向后走end++,

不够的话,start向后退,这样就能够在油量不够的时候往后遍历新的出发点,最后start == end 的时候,如果有解就是start的位置。

class Solution { public: int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { int start = gas.size() - 1; int end = 0; int sum = gas[start] - cost[start]; while( start > end){ if(sum >= 0){ sum += gas[end] - cost[end]; end++; } else{ start--; sum += gas[start] - cost[start]; } } return sum >= 0 ? start : -1; } };
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/7/28 17:21:05

WPF控件游标与十字线设计及交互优化

1. WPF控件中的游标与十字线设计解析 在WPF应用开发中&#xff0c;控件交互设计直接影响用户体验。游标&#xff08;Cursor&#xff09;和十字线&#xff08;Crosshair&#xff09;作为两种常见的视觉反馈元素&#xff0c;分别承担着不同的交互提示功能。游标用于指示当前鼠标位…

作者头像 李华
网站建设 2026/7/28 17:15:52

早起原来还有这些好处

昨天中午吃完午饭散步的时候&#xff0c;看了半佛仙人公众号中推荐的一篇文章《 为什么优秀的人&#xff0c;都把闹钟定在早晨5&#xff1a;57》&#xff0c;感觉写的非常不错&#xff0c;就简单的总结了一下。 早起&#xff0c;是一个非常好的习惯&#xff0c;博主认为这是一件…

作者头像 李华
网站建设 2026/7/28 17:14:01

HS2-HF补丁:10分钟打造你的专属Honey Select 2游戏体验

HS2-HF补丁&#xff1a;10分钟打造你的专属Honey Select 2游戏体验 【免费下载链接】HS2-HF_Patch Automatically translate, uncensor and update HoneySelect2! 项目地址: https://gitcode.com/gh_mirrors/hs/HS2-HF_Patch 你是否曾经因为语言障碍而错过了Honey Selec…

作者头像 李华
网站建设 2026/7/28 17:12:54

Sunshine游戏串流服务器终极指南:5分钟搭建家庭云游戏系统

Sunshine游戏串流服务器终极指南&#xff1a;5分钟搭建家庭云游戏系统 【免费下载链接】Sunshine Self-hosted game stream host for Moonlight. 项目地址: https://gitcode.com/GitHub_Trending/su/Sunshine Sunshine是一款开源的自托管游戏串流服务器&#xff0c;专为…

作者头像 李华
网站建设 2026/7/28 17:09:54

数据结构实验(C语言):顺序串

文章参考过网上的内容&#xff0c;如有侵权&#xff0c;请联系 #include <stdio.h> #include <stdlib.h>typedef struct {char data[100]; //初始化串int len; //串长 }SqString;void DispStr(SqString s) {int i;if (s.len>0){for (i0;i<s.len;i)printf(&…

作者头像 李华
网站建设 2026/7/28 17:06:44

进程互斥和进程同步

一、进程互斥由于进程具有独立性和异步性等并发特征&#xff0c;计算机的资源有限&#xff0c;导致了进程之间的资源竞争和共享&#xff0c;也导致了对进程执行过程的制约。1、临界资源和临界区&#xff08;临界部分&#xff09;临界资源&#xff1a;一次只能供一个进程访问的资…

作者头像 李华