Leetcode——貪心算法gas-station

gas-station

題目描述:
There are N gas stations along a circular route, where the amount of gas at station i isgas[i].

You have a car with an unlimited gas tank and it costscost[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.
知識點:
貪心算法
解題思路:
【個人思路】
首先要理解題意,在一條環形路上有N個加氣站,站點i的氣的體積爲gas[i],你有一輛車氣罐體積不受限,當從站點i到下一個站點i+1消耗氣的體積爲cost[i]。找到一個可以作爲起點的站點,使得從該站點出發可以遍歷完整個環形的道路,否則返回-1。
我們需要明確以下兩個問題:
1.若gas的總量>=cost的總量,那麼一定存在一條解決路徑。
2.尋找起點:設置起點res=0;依次迭代到i,若resgas+=gas[i]-cost[i],一旦在i處遇到resgas<0,那麼說明當前選擇的起始點不行,需要重新選擇。重設res=i+1,重複迭代過程。
具體代碼:

public class Solution {
  public int canCompleteCircuit(int[] gas, int[] cost) {
      		int len=gas.length;
  	int resgas=0;
  	int res=0;
  	int total=0;         //驗證整個數組是否gas>cost
  	for(int i=0;i<len ;i++){
  		resgas+=gas[i]-cost[i];
  		if(resgas<0){
  			total+=resgas;
  			resgas=0;
  			res=i+1;
  		}
  	}
  	total+=resgas;
  	return total<0 ? -1:res % len;
  }
}

注意點
一開始拿到這個題有點懵,沒有理清楚這個題的具體讓幹嘛,拿到這種題首先要從題目中獲取信息然後根據問題入手。既然是貪心算法,那麼就是遍歷但是如何遍歷,遍歷截止的條件是什麼,這些都是從題目中獲取的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章