https://leetcode.com/problems/gas-station/
来源:互联网 发布:mysql 开启慢日志 编辑:程序博客网 时间:2024/06/06 21:02
https://leetcode.com/problems/gas-station/
这道题暴力的解释可以的 但是超时
def canCompleteCircuit(gas, cost): length=len(gas) for i in range(length): sgas=0 scos=0 for j in range(length): if i+j<length: sgas=sgas+gas[i+j] scos=scos+cost[i+j] else: sgas=sgas+gas[j-i-1] scos=scos+cost[j-i-1] if sgas<scos: break else: if j==length-1: return i return -1
后来想不到别的算法 然而有个网友给了一些可以提高效率的方法
假设从A到P都能正常走 然而从A到P+1点发现走到半路没有油了
那么 下次走 直接从P+1点开始做起点
从A和P+1中间的任何一点都不能顺利走到P+1
原因在于 假设C点开始走 那么因为A能走到C 说明 A到C后邮箱里的油Lac是》=0
从A到P+1点油小于0 从C到P+1 邮箱里还少了从A到C的Lac的量的油 更不可能走到P+1点了
class Solution: # @param {integer[]} gas # @param {integer[]} cost # @return {integer} def canCompleteCircuit(self,gas, cost): length=len(gas) list=[] for i in range(length): list.append(gas[i]-cost[i]) start=0 while start<length: sum=0 n=0 for j in range(length): sum=sum+list[(start+j)%length] n=n+1 if sum<0: start=start+n break if j==length-1 and sum>=0: return start return -1
0 0
- https://leetcode.com/problems/gas-station/
- https://leetcode.com/problems/candy/
- https://leetcode.com/problems/sqrtx/
- LeetCode:Gas Station
- [LeetCode] Gas Station
- [leetcode]Gas Station
- Leetcode: Gas Station
- LeetCode:Gas Station
- [LeetCode] Gas Station
- leetcode Gas Station
- [LeetCode]Gas Station
- LeetCode 之 Gas Station
- leetcode Gas Station
- 【Leetcode】Gas Station
- LeetCode | Gas Station
- LeetCode之Gas Station
- Leetcode: Gas Station
- LeetCode OJ:Gas Station
- Swift-可选类型(Optional)以及解包
- C++成员变量的初始化顺序问题
- 深入理解DIP、IoC、DI以及IoC容器
- Unity中批处理对Shader的影响
- Use of delimiter on Stored Procedure in MySQL
- https://leetcode.com/problems/gas-station/
- 链式栈的基本操作——LinkStack(C语言版)
- #笔记#圣思园 JavaSE 第53讲——泛型详解(1)
- 【算法思想】位图排序算法
- 五大常用算法之四:回溯法
- linux学习笔记—杂项1
- RecommenderIntro
- Android Studio 1.0.1 + Genymotion安卓模拟器打造高效安卓开发环境
- Android控件的一些属性