【代码随想录】刷题笔记Day36

前言

  • 打球运动量不饱和,不太爽,来刷题爽爽

134. 加油站 - 力扣(LeetCode)

  • 难点在于环形遍历,实际上和最大子序和的思路很像,小于0就从下个位置开始
  • 局部最优: 当前累加rest[i]的和curSum一旦小于0,起始位置至少要是i+1,因为从i之前开始一定不行。**全局最优:**找到可以跑一圈的起始位置
cpp 复制代码
// 暴力法:两层for,用while模拟环形
class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        for (int i = 0; i < cost.size(); i++) {
            int rest = gas[i] - cost[i]; // 记录剩余油量
            int index = (i + 1) % cost.size();
            while (rest > 0 && index != i) { // 模拟以i为起点行驶一圈(如果有rest==0,那么答案就不唯一了)
                rest += gas[index] - cost[index];
                index = (index + 1) % cost.size();
            }
            // 如果以i为起点跑一圈,剩余油量>=0,返回该起始位置
            if (rest >= 0 && index == i) return i;
        }
        return -1;
    }
};
cpp 复制代码
// 贪心法,一层for
class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int curSum = 0;  // 当前汇总剩余油量
        int totalSum = 0;  // 用于看最后能否走完
        int start = 0;
        for (int i = 0; i < gas.size(); i++) {
            curSum += gas[i] - cost[i];
            totalSum += gas[i] - cost[i];
            if (curSum < 0) {   // 当前累加rest[i]和 curSum一旦小于0
                start = i + 1;  // 起始位置更新为i+1
                curSum = 0;     // curSum从0开始
            }
        }
        if (totalSum < 0) return -1; // 说明怎么走都不可能跑一圈了
        return start;  // 总和大于等于0说明能走完
    }
};

后言

  • 一道题就看了一小时了(主要是要自己想就折腾),效率还是有点低的
相关推荐
cici158744 小时前
基于GPRMAX的地下管线正演模拟与MATLAB实现
开发语言·算法·matlab
副露のmagic4 小时前
更弱智的算法学习 day16
数据结构·学习·算法
@zulnger4 小时前
python 学习笔记(文件读写)
笔记·python·学习
DeepVis Research4 小时前
【Storage/Signal】2026年度非线性存储一致性与跨时域信号处理基准索引 (Benchmark Index)
算法·网络安全·数据集·分布式系统
liliangcsdn4 小时前
VAE中Encoder和Decoder的理论基础的探索
人工智能·算法·机器学习
韩明君4 小时前
debian13学习笔记
服务器·笔记·学习
Love Song残响5 小时前
30字高效MATLAB优化指南
数据结构·算法
sin_hielo5 小时前
leetcode 1975
数据结构·算法·leetcode
2501_941820495 小时前
面向零信任安全与最小权限模型的互联网系统防护设计思路与多语言工程实践分享
开发语言·leetcode·rabbitmq
彩色面团儿5 小时前
Pytest框架测试用例分析(测试笔记二)
笔记·测试用例·pytest