zoukankan      html  css  js  c++  java
  • Leetcode之贪心算法

    持续更新。。。

    github链接:https://github.com/x2mercy/Leetcode_Solution

    今天第一次遇到贪心算法。

    基本思路来自百度百科

    贪心算法参考:http://blog.csdn.net/qq_32400847/article/details/51336300

    Jump Game(LC 55 Medium)

    Given an array of non-negative integers, you are initially positioned at the first index of the array.

    Each element in the array represents your maximum jump length at that position.

    Determine if you are able to reach the last index.

    For example:
    A = [2,3,1,1,4], return true.

    A = [3,2,1,0,4], return false.

    代码:

    class Solution(object):
        def canJump(self, nums):
            """
            :type nums: List[int]
            :rtype: bool
            """
            max_jump=0
            for i in range(len(nums)):
                if i>max_jump:
                    return False
                else:
                    max_jump=max(max_jump,nums[i]+i)
                    if max_jump==len(nums)-1:
                        break
            return True
            

    1. 贪心算法考虑每个元素能跳的最大距离

    2. 判断是否可以到达最后一个元素取决于最后的max_jump是不是=len(nums)-1,如果等于,即可跳出循环,返回True

    3. 为什么要考虑每个元素能跳的最大距离呢?——贪心算法核心

     以这种情况为例:

          2,3,1,1,4

    index:  0   1   2  3   4

     遍历到i=1时,已经可以跳到最后一个元素了,即nums[1]+1=4,此时即可判断为True

    为什么?

    因为i=0时,可最大跳到i=2的元素,则它也可以只跳一个元素,即跳到i=1,nums[1]=3的元素,然后由3直接跳到最后

    那么!如果是0,3,1,1,4呢?3也可以直接跳到最后,但是其实结果应该是False,因为第一个元素为0,永远跳不到第二个元素

    这种情况要怎么做呢?

    加一个if

    if i>max_jump: return False

    这种情况,i=0时,max_jump卡在0,则当i+1=1时,i>max_jump,直接返回False了

    所以:在计算max_jump之前,我们要先比较上一个max_jump能不能更新到当前的i,如果不能,后面的都是放屁,直接False

    Gas Station (LC134 Medium)

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

    You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.

    Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.

    Note:
    The solution is guaranteed to be unique.

    class Solution(object):
        def canCompleteCircuit(self, gas, cost):
            """
            :type gas: List[int]
            :type cost: List[int]
            :rtype: int
            """
            if len(gas)==1:
                if gas[0]>=cost[0]:
                    return 0
                else:
                    return -1
            diff=[]
            for i in range(len(gas)):
                diff.append(gas[i]-cost[i])
            sum_gas=0
            index=0
            before=0
            for i in range(len(diff)):
                if sum_gas<before:
                    before=sum_gas
                    index=i
                sum_gas=sum_gas+diff[i]
            if sum_gas<0:
                return -1
            return index
                
            

    这道题的思考可以分成两部分,一部分是:是否可以走完一个循环,另一个是:如果可以,怎么计算index

    首先,是否可以走完一个循环:计算所有的diff=gas[i]-cost[i],所有的diff的和sum_gas,因为无论从哪里开始走,sum_gas都一样

    如果sum_gas<0,则可以直接返回-1

    如果sum_gas>0,则进入第二个问题,怎么计算index

    对于这个问题,本来是准备在判断完sum_gas之后再计算的,但是这样却需要重新遍历每个gas station,然后逐个把diff加起来

    这样,又回到了最初的那个循环,所以索性在最开始的循环里加语句:

    怎么样判断是从哪个index开始呢?

    从一个例子看:

    gas: 1  2  3  3

    cost:2 1  5   1

    diff: -1 1 -2 2

    这个例子的答案是3,要从3开始循环才能走完整个循环

    为什么?

    看diff,i=0的元素是-1,不可能从0开始;i=1的元素是1,可能从这个元素开始么?

    不可能

    为什么?

    因为如果从i=1开始,那进行到i=2时,diff=-2,1+(-2)=-1,这样进行不到下个gas station!

    所以回到最初的问题:该如何计算index?

    i=0, sum_gas=-1

    i=1, sum_gas=-1+1=0

    i=2, sum_gas=0+(-2)=-2

    i=3, sum_gas=-2+2=0

    发现:凡是被pass掉的index对应的sum_gas都比前一个sum_gas要小

    而正确的index对应的sum_gas要大于前一个sum_gas

    所以可以在循环的开始加上一个判断,注意!要加在计算当前i的sum_gas之前!即:当前判断所用的sum_gas还是上一个元素对应的

    如果(上一个元素的)sum_gas<before,则先把(上一个元素的)sum_gas赋给before以便之后比较,然后把当前的i暂赋给index

    然后再计算当前i对应的sum_gas,以便下一个循环使用

    最后跳出循环,返回index

  • 相关阅读:
    Mybatis3详解(一)----Mybatis的介绍
    【k8s】svc-sessionAffinityConfig
    【k8s】svc-sessionAffinity
    【k8s】svc-selector
    【k8s】svc-publishNotReadyAddresses
    【k8s】svc-ports
    【k8s】svc-externalIPs
    【k8s】svc-clusterIPs
    【k8s】svc-clusterIP
    【k8s】Service
  • 原文地址:https://www.cnblogs.com/x1mercy/p/7976558.html
Copyright © 2011-2022 走看看