当前位置: 首页 > news >正文

面试经典150题——Day14

文章目录

    • 一、题目
    • 二、题解

一、题目

134. Gas Station

There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i].

You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith 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

Example 1:

Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2]
Output: 3
Explanation:
Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 4. Your tank = 4 - 1 + 5 = 8
Travel to station 0. Your tank = 8 - 2 + 1 = 7
Travel to station 1. Your tank = 7 - 3 + 2 = 6
Travel to station 2. Your tank = 6 - 4 + 3 = 5
Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
Therefore, return 3 as the starting index.
Example 2:

Input: gas = [2,3,4], cost = [3,4,3]
Output: -1
Explanation:
You can’t start at station 0 or 1, as there is not enough gas to travel to the next station.
Let’s start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 0. Your tank = 4 - 3 + 2 = 3
Travel to station 1. Your tank = 3 - 3 + 3 = 3
You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
Therefore, you can’t travel around the circuit once no matter where you start.

Constraints:

n == gas.length == cost.length
1 <= n <= 105
0 <= gas[i], cost[i] <= 104

题目来源: leetcode

二、题解

贪心算法

class Solution {
public:int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {int currentSum = 0;int totalSum = 0;int index = 0;for(int i = 0;i < gas.size();i++){currentSum += gas[i] - cost[i];totalSum += gas[i] - cost[i];if(currentSum < 0) currentSum = 0,index = i + 1;}if(totalSum < 0) return -1;else return index;}
};
http://www.lryc.cn/news/197951.html

相关文章:

  • Pika v3.5.1发布!
  • Kotlin中的数组
  • (3) OpenCV图像处理kNN近邻算法-识别摄像头数字
  • 上海亚商投顾:沪指震荡调整 转基因概念股逆势大涨
  • abap中程序跳转(全)
  • 启动速度提升 10 倍:Apache Dubbo 静态化方案深入解析
  • PCB命名规则-allegro
  • [架构之路-240]:目标系统 - 纵向分层 - 应用层 - 应用层协议与业务应用程序的多样化,与大自然生物的丰富多彩,异曲同工
  • 探索数字时代的核心:服务器如何塑造未来并助你成就大业
  • spring6-资源操作:Resources
  • C语言 内存
  • Java设计模式之备忘录模式
  • 深度学习 | Pytorch深度学习实践
  • Elasticsearch7.9.3保姆级安装教程
  • 深入使用探讨 PuppeteerSharp 抓取 LinkedIn 页面的步骤
  • 联合体(共用体)
  • 从零开始:GitFlow详细教程,轻松掌握分支策略
  • 深度学习硬件介绍
  • 利用向导创建MFC
  • MySQL 8.0 OCP认证精讲视频、环境和题库之五 事务、缓存
  • ACL配置
  • 微信小程序修改van-popup的背景颜色
  • SpringCloud-Nacos
  • 动态规划12(Leetcode221最大正方形)
  • 【Git】bad signature 0x00000000 index file corrupt. fatal: index file corrupt
  • GO 语言的函数??
  • 机器学习基础之《回归与聚类算法(3)—线性回归优化:岭回归》
  • DirectX3D 正交投影学习记录
  • 数据挖掘十大算法--Apriori算法
  • [蓝桥杯 2022 省 B] 统计子矩阵