码农知识堂 - 1000bd
  •   Python
  •   PHP
  •   JS/TS
  •   JAVA
  •   C/C++
  •   C#
  •   GO
  •   Kotlin
  •   Swift
  • 134. 加油站


    解法1

    暴力模拟 + 缓存

    走过的路,没走通。说明:中间节点也是不通的。

    1. class Solution {
    2. boolean[] visited;
    3. private boolean canComplete(int[] gas, int[] cost, int start) {
    4. if (visited[start]) {
    5. return false;
    6. }
    7. int n = gas.length;
    8. int totalGas = 0;
    9. int now = start;
    10. while (true) {
    11. visited[now] = true;
    12. totalGas += gas[now];
    13. if (totalGas < cost[now]) {
    14. return false;
    15. }
    16. totalGas -= cost[now];
    17. now++;
    18. if (now == n) {
    19. now = 0;
    20. }
    21. if (now == start) {
    22. return true;
    23. }
    24. }
    25. }
    26. public int canCompleteCircuit(int[] gas, int[] cost) {
    27. int n = gas.length;
    28. visited = new boolean[n];
    29. for (int start = 0; start < n; start++) {
    30. if (canComplete(gas, cost, start)) {
    31. return start;
    32. }
    33. }
    34. return -1;
    35. }
    36. }

    解法2

    走过的路,没走通。说明:中间节点也是不通的。

    优化效率。

    1. class Solution {
    2. public int canCompleteCircuit(int[] gas, int[] cost) {
    3. int n = gas.length;
    4. for (int i = 0; i < n; i++) {
    5. gas[i] -= cost[i];
    6. }
    7. for (int start = 0; start < n; start++) {
    8. int totalGas = 0, now = start, next = start;
    9. while (true) {
    10. if (now > next) {
    11. next = now;
    12. }
    13. totalGas += gas[now++];
    14. if (totalGas < 0) {
    15. break;
    16. }
    17. if (now == n) {
    18. now = 0;
    19. }
    20. if (now == start) {
    21. return now;
    22. }
    23. }
    24. start = next;
    25. }
    26. return -1;
    27. }
    28. }

  • 相关阅读:
    反转链表的几种方式(兼顾每日刷题Day15)
    ​iOS安全加固方法及实现
    Redis学习记录------Redis6的事务操作(九)
    Arduino ESP32使用U3115S芯片控制H桥驱动有刷直流电机
    某通电子文档安全管理系统 CDGAuthoriseTempletService1接口SQL注入漏洞复现 [附POC]
    如何利用AI技术优化独立站客服系统?听听专家怎么说!
    罗茨气体流量计的结构设计
    【图形学】15 UnityShader语义(三)
    【源码编译】Apache SeaTunnel-Web 适配最新2.3.4版本教程
    素数计算 马蹄集
  • 原文地址:https://blog.csdn.net/diOSyu/article/details/139483735
  • 最新文章
  • 沪漂五周年了:我越来越迷茫了
    Agentic Skill Routing 实战:别再把所有 Skill 塞进 AI Agent 上下文
    MySQL-Seconds_behind_master的精度误差
    [MAF预定义ChatClient中间件-03]CachingChatClient——利用缓存省钱省时间
    AI的至暗历史:从万众期待到被政府撤资,AI的两次死亡徘徊
    Agent OS :五种驯服不确定性的范式
    PortSwigger SQL注入LAB11
    数据库即时编译JIT
    [Begin]AI Learn Data Day 0
    深度学习进阶(二十七)现代 LLM 的核心架构设计其二:SwiGLU
  • 热门文章
  • 十款代码表白小特效 一个比一个浪漫 赶紧收藏起来吧!!!
    奉劝各位学弟学妹们,该打造你的技术影响力了!
    五年了,我在 CSDN 的两个一百万。
    Java俄罗斯方块,老程序员花了一个周末,连接中学年代!
    面试官都震惊,你这网络基础可以啊!
    你真的会用百度吗?我不信 — 那些不为人知的搜索引擎语法
    心情不好的时候,用 Python 画棵樱花树送给自己吧
    通宵一晚做出来的一款类似CS的第一人称射击游戏Demo!原来做游戏也不是很难,连憨憨学妹都学会了!
    13 万字 C 语言从入门到精通保姆级教程2021 年版
    10行代码集2000张美女图,Python爬虫120例,再上征途
小工具 小游戏
Copyright © 2022 侵权请联系2656653265@qq.com    京ICP备2022015340号-1

京公网安备 11010502049817号