【Leetcode】Gas Station
2016-05-29 21:42
330 查看
题目链接:https://leetcode.com/problems/gas-station/
题目:
There are N gas stations along a circular route, where the amount of gas at station i is
You have a car with an unlimited gas tank and it costs
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.
思路:
看了tag发现是贪心,想起老师上课说贪心实现起来是最简单的,最难的是证明贪心策略的正确性。这里主要为了AC,多尝试几次可能的策略懒得证明了(宝宝TM不会证明啊!!)。很自然想到的策略有:1、从gas最多的station开始 2、从cost最少的station开始 3、从剩余(gas-cost)最少的开始。
尝试了几次发现第二种是对的,但要注意如果有多个站点cost相同,要判断这些站点是否能完成环圈旅行。
算法:
题目:
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.
思路:
看了tag发现是贪心,想起老师上课说贪心实现起来是最简单的,最难的是证明贪心策略的正确性。这里主要为了AC,多尝试几次可能的策略懒得证明了(宝宝TM不会证明啊!!)。很自然想到的策略有:1、从gas最多的station开始 2、从cost最少的station开始 3、从剩余(gas-cost)最少的开始。
尝试了几次发现第二种是对的,但要注意如果有多个站点cost相同,要判断这些站点是否能完成环圈旅行。
算法:
public int canCompleteCircuit(int[] gas, int[] cost) { int index = 0; for (int i = 1; i < cost.length; i++) { if (cost[i]<cost[index]) { index = i; } } for(int i=0;i<cost.length;i++){ if(cost[i]==cost[index]){ if(isValid(cost, gas, i)!=-1){ return i; } } } return -1; } public int isValid(int[]cost,int[] gas,int index){ int tankGas = 0; for(int i=index;i<gas.length;i++){ tankGas+=gas[i]-cost[i]; if(tankGas<0){ return -1; } } for(int i=0;i<index;i++){ tankGas+=gas[i]-cost[i]; if(tankGas<0){ return -1; } } return index; }
相关文章推荐
- 【Leetcode】Next Permutation
- 图片的HTTP请求
- java基础第十四天
- nyoj 47 过河问题
- LightOj 1045 N!位数的应用
- 触发器解决外键约束问题
- Android中xml和json文件的解析和创建
- 评教维护--成长之路
- Go语言的并发和并行
- 《太阳的后裔》OST.5 Once again
- 【Leetcode】Recover Binary Search Tree
- mysql 优化(5)索引与排序
- K均值聚类算法及MATLAB函数使用
- 【struts1】--Servlet讲解MVC框架基本原理
- [KD TREE] BZOJ 3053 The Closest M Points
- 守护进程-解析
- Android 基础总结:(七)BroadcastReceiver详解(上)
- 【Leetcode】Longest Palindromic Substring
- Eclipse debug断点调试代码时出现source not found问题
- BSOJ: 3748 【USACO 2006 March Gold】Milk Team Select产奶比赛