leetcode -- Gas Station -- 跟jump game像,重点--贪心

https://leetcode.com/problems/gas-station/

类比jump game https://leetcode.com/problems/jump-game/

思路1:贪心 O(n)

思路就是贪心。子问题就是判断车在第i个position的时候是否可以到达i+1个position,条件就是当前第i个position所加的油gas[i] + diff(就是到达第i个position时剩下来的油,可以看做前面几站提供的补给) 大于等于cost[i]。

这里首先要判断当sum(gas) < sum(cost)则无解。

res_index 初始化为0
然后从i = 0开始,逐渐递增,直到第i个站不能到达第i+1个站的话,常规思路就是再令res_index ==1,然后继续i = res_index开始递增,。。。直到找到res_index. 这就是常规的O(n^2)思路。但是会TLE.

其实在res_index = 0, 然后遇到第i = k个站不能到达第i+1个站,这个时候其实只需要继续试探 res_index> i就行,因为如果从 0< res_index <i+1 <script type="math/tex" id="MathJax-Element-13"> 0< res_index <i+1 <script type="math/tex" id="MathJax-Element-15">

其实这里res_index从k+1开始试探,数值上也不一定能保证,能车子能从第k站到第k+1站,e.g. 第k站到第k+1站路途遥远,耗油非常大。因为这里题目保证了肯定有解,那么就可以消除这个顾虑了

class Solution(object):
    def canCompleteCircuit(self, gas, cost):
        """
        :type gas: List[int]
        :type cost: List[int]
        :rtype: int
        """
        if sum(gas) < sum(cost): return -1
        n = len(gas)
        diff = 0
        stationIndex = 0
        for i in range(n):
            if gas[i]+diff < cost[i]: stationIndex = i+1; diff = 0
            else: diff += gas[i]-cost[i]
        return stationIndex

思路2:常规遍历 O(n^2)

这里要想到如果把O(n^2)降到O(n)
自己的办法是O(n^2)的,所以TLE了。

class Solution(object):
    def canCompleteCircuit(self, gas, cost):
        """
        :type gas: List[int]
        :type cost: List[int]
        :rtype: int
        """
        if sum(gas) < sum(cost): return -1
        for i in xrange(len(cost)):
            balance = gas[i]
            j = i + 1

            while j < len(cost):
                #print (j, balance, cost[j-1])
                if balance < cost[j-1]:
                    break
                else:
                    balance = balance - cost[j - 1] + gas[j]
                j += 1
            #print 'part1 = %d %d' %(i,j)
            if j != len(cost):
                continue

            j = 0
            while j <= i:
                if balance < cost[j - 1]:
                    break
                else:
                    balance = balance - cost[j - 1] + gas[j]
                j += 1
            #print 'part2 = %d %d' %(i,j)
            if j != i + 1:
                continue
            return i
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值