1.22刷题日记:贪心算法

文章讨论了解决LeetCode上的两个编程问题:在给定数组中判断是否可以通过跳跃到达终点(跳跃游戏)和确定可以从哪个加油站开始绕环路一周(加油站问题)。提供了两种算法的Python代码实现,并强调了解题思路和优化关键点。
摘要由CSDN通过智能技术生成

55. 跳跃游戏

给你一个非负整数数组 nums ,你最初位于数组的 第一个下标 。数组中的每个元素代表你在该位置可以跳跃的最大长度。

判断你是否能够到达最后一个下标,如果可以,返回 true ;否则,返回 false 。

这题和昨天的差不多,我就直接看了一下题解

示例 1:

输入:nums = [2,3,1,1,4]
输出:true
解释:可以先跳 1 步,从下标 0 到达下标 1, 然后再从下标 1 跳 3 步到达最后一个下标。
class Solution:
    def canJump(self, nums: List[int]) -> bool:
        max_i = 0       #初始化当前能到达最远的位置
        for i, jump in enumerate(nums):   #i为当前位置,jump是当前位置的跳数
            if max_i>=i and i+jump>max_i:  #如果当前位置能到达  
                max_i = i+jump  #更新最远能到达位置
        return max_i>=i

代码解释:变量max_i来表示当前能够到达的最远位置。然后使用循环遍历数组,对于每个位置,判断当前位置是否可以到达,并且更新最远能到达的位置max_i。最后判断max_i是否大于等于数组的最后一个位置,如果是则返回True,表示可以跳跃到最后一个位置,否则返回False。

对于for i,jump in enumerate(nums):

这里的jump是指数组nums中当前位置i所能跳跃的最大长度,因为在for循环中使用了enumerate(nums),所以jump实际上是nums[i],所以这里可以写成i+nums[i]>max_i,就可以达到同样的效果。

134. 加油站

在一条环路上有 n 个加油站,其中第 i 个加油站有汽油 gas[i] 升。

你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发,开始时油箱为空。

给定两个整数数组 gas 和 cost ,如果你可以按顺序绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1 。如果存在解,则 保证 它是 唯一 的。

示例 1:

输入: gas = [1,2,3,4,5], cost = [3,4,5,1,2]
输出: 3
解释:
从 3 号加油站(索引为 3 处)出发,可获得 4 升汽油。此时油箱有 = 0 + 4 = 4 升汽油
开往 4 号加油站,此时油箱有 4 - 1 + 5 = 8 升汽油
开往 0 号加油站,此时油箱有 8 - 2 + 1 = 7 升汽油
开往 1 号加油站,此时油箱有 7 - 3 + 2 = 6 升汽油
开往 2 号加油站,此时油箱有 6 - 4 + 3 = 5 升汽油
开往 3 号加油站,你需要消耗 5 升汽油,正好足够你返回到 3 号加油站。
因此,3 可为起始索引。

一开始写的超出时间限制了:

class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        if sum(gas)<sum(cost):
            return -1
        n=len(gas)
        def gas_cost(gas: List[int], cost: List[int])->int:
            remain=[]
            for i in range(n):
                remain.append(gas[i]-cost[i])
            return remain
        remain=gas_cost(gas,cost)
        res=0
        total=0
        for i in range(n):
            if remain[i]>=0:
                res=i
                sub_list=remain[0:i]
                total=remain[i]
                for j in range(i+1,n):
                    if total<0:
                        break
                    total+=remain[j]
                if total>=0:
                    for j in sub_list:
                        if total<0:
                            break
                        total+=j
                if total>=0:
                    return res
        
        return -1
                    

        


最终代码: (最后实在想不到方法,看了评论区和我想法比较接近的一位:)

class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        
        '''总油量 < 总耗油量,一定无解'''
        if sum(gas) < sum(cost):
            return -1
        
        '''sum(gas) >= sum(cost),一定有解【题目保证唯一解】'''
        n = len(gas)
        start = 0       # 记录出发点,从索引0开始
        total = 0       # 记录汽车实际油量
        for i in range(n):
            total += gas[i] - cost[i]  # 每个站点加油量相当于 gas[i] - cost[i]
            if total < 0:       # 在i处的油量<0,说明从之前站点出发的车均无法到达i
                start = i+1     # 尝试从下一个站点i+1重新出发
                total = 0       # 重新出发时油量置为0
        
        return start    # 解是唯一的

作者:flix
链接:https://leetcode.cn/problems/gas-station/solutions/1399702/by-flix-fhpm/

if total < 0:       # 在i处的油量<0,说明从之前站点出发的车均无法到达i

                start = i+1     # 尝试从下一个站点i+1重新出发

                total = 0       # 重新出发时油量置为0
这点很重要,但是我没有想到,所以设置的循环浪费了很多时间,

 

error execution phase preflight: [preflight] Some fatal errors occurred: [ERROR ImagePull]: failed to pull image k8s.gcr.io/kube-apiserver:v1.22.17: output: Error response from daemon: Ge t "https://k8s.gcr.io/v2/": net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers), error: exit status 1 [ERROR ImagePull]: failed to pull image k8s.gcr.io/kube-controller-manager:v1.22.17: output: Error response from d aemon: Get "https://k8s.gcr.io/v2/": net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers), error: exit status 1 [ERROR ImagePull]: failed to pull image k8s.gcr.io/kube-scheduler:v1.22.17: output: Error response from daemon: Ge t "https://k8s.gcr.io/v2/": net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers), error: exit status 1 [ERROR ImagePull]: failed to pull image k8s.gcr.io/kube-proxy:v1.22.17: output: Error response from daemon: Get "h ttps://k8s.gcr.io/v2/": net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers), error: exit status 1 [ERROR ImagePull]: failed to pull image k8s.gcr.io/pause:3.5: output: Error response from daemon: Get "https://k8s .gcr.io/v2/": context deadline exceeded, error: exit status 1 [ERROR ImagePull]: failed to pull image k8s.gcr.io/etcd:3.5.0-0: output: Error response from daemon: Get "https:// k8s.gcr.io/v2/": net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers), error: exit status 1 [ERROR ImagePull]: failed to pull image k8s.gcr.io/coredns/coredns:v1.8.4: output: Error response from daemon: Get "https://k8s.gcr.io/v2/": context deadline exceeded, error: exit status 1 [preflight] If you know what you are doing, you can make a check non-fatal with `--ignore-preflight-errors=...` To see the stack trace of this error execute with --v=5 or higher
07-12
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值