leetcode14.gasStation
来源:互联网 发布:2015网络歌曲大全 编辑:程序博客网 时间:2024/05/17 06:28
问题描述如下:
There are N gas stations along a circular route, where the amount of gas at stationi isgas[i]
.
You have a car with an unlimited gas tank and it costs cost[i]
of gas to travel from stationi 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.
package leetcode13.gasStation;import java.util.Arrays;/** * Gas Station * * 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. */public class Solution {public static void main(String[] args) {int[] gas = {3,4,4,3};int[] cost = {4,3,2,4};System.out.println(canCompleteCircuit(gas, cost));}// O(n) DPpublic static int canCompleteCircuit(int []gas, int[] cost){int curGas=0;int total=0;int startIndex=0;for(int i=0;i<gas.length;i++){int curRemain=gas[i]-cost[i];if(curGas>=0){curGas+=curRemain;}else{curGas=curRemain;startIndex=i;}total+=curRemain;}return total>0?startIndex:-1;}}
总结:可以利用暴力的O(N^2)的方法,当然更好的办法是利用DP(动态规划)
0 0
- leetcode14.gasStation
- leetcode14
- leetcode14
- leetcode14
- leetcode14
- Leetcode14
- leetcode gasstation
- Leetcode - GasStation
- Leetcode gasstation
- Leetcode14: Longest Common Prefix
- [LeetCode14] Longest Common Prefix
- Leetcode14: House Robber
- leetcode14 Longest Common Prefix
- leetcode14 Longest Common Prefix
- LeetCode14:Longest Common Prefix
- LeetCode14. Longest Common Prefix
- leetcode14,Longest Common Prefix
- Leetcode14. Longest Common Prefix
- 逻辑回归logistic regression
- c++学习书籍之《C++primer》评价
- leetcode-3sumclosest
- spring html5 拖拽上传多文件
- 模块管理常规功能自定义系统的设计与实现(51--功能更新[1] 对父模块的链接显示)
- leetcode14.gasStation
- android Universal Image Loader for Android 说明文档 (1)
- 阿里云服务器挂载数据盘以及环境安装
- java定时任务,每天定时执行任务
- 神经网络
- Hadoop的回收机制
- Android获取图片类型
- leetcode15.candy
- Eclipse 3.5.2、MyEclipse 8.5 版本安装Aptana插件