持續更新。。。
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