开始学算法1
来源:互联网 发布:js幻灯片轮播代码 编辑:程序博客网 时间:2024/06/06 03:00
在一条环路上有 N 个加油站,其中第 i 个加油站有汽油gas[i],并且从第i个加油站前往第i+1个加油站需要消耗汽油cost[i]。
你有一辆油箱容量无限大的汽车,现在要从某一个加油站出发绕环路一周,一开始油箱为空。
求可环绕环路一周时出发的加油站的编号,若不存在环绕一周的方案,则返回-1。
public class Solution { /* * @param gas: An array of integers * @param cost: An array of integers * @return: An integer */ public int canCompleteCircuit(int[] gas, int[] cost) { //循环遍历所有位置 for(int i=0;i<gas.length;i++){ int now=0; //连第一站都无法开出,搜索下一个 if(gas[i]<cost[i]) continue; else { int pos;//汽车位置 int getReal=gas[i]-cost[i];//真实的耗油量 now+=getReal;//现有油量 for(pos=(i+1)%gas.length;pos!=i&&now>0;pos=(pos+1)%gas.length){ getReal=gas[pos]-cost[pos]; now+=getReal;//现有油量 } //满足条件,返回起始站点位置 if(pos==i&&now>=0) return i; } //均不满足条件 return -1; }}
总的思路就是循环遍历,不满足条件的就跳过。没什么好说的,应该有更好的方法来解决这个问题。
阅读全文
0 0
- 开始学算法1
- 开始学算法导论
- 从头开始学算法
- 零开始学算法
- 开始对算法和数学感兴趣了。
- 【从头开始学算法】快速排序
- 【从头开始学算法】归并排序
- 开始学算法的第一天
- 一步一步学grails:1 开始
- 从“1”开始学python
- 开始学
- 开始学数据结构和算法了,,坚持把代码出来
- 【从头开始学算法】选择排序 插入排序 冒泡排序
- 今天开始学Eclipse/SWT(1)
- 今天开始学Eclipse/SWT(1)
- 40岁开始学Linux(1)-Makefile
- 从头开始学c ----基础1
- 开始学数据库了(1)
- 作业四 链队列
- office 2016优化
- 495. Teemo Attacking
- 视频编解码质量评价---BDBR与BD-PSNR
- 归并排序
- 开始学算法1
- concurrent-7-AQS-CountDownLatch,CyclicBarrier
- C语言:探测 unsigned int 的边界
- [洛谷P2375]动物园
- fclose函数的一个注意点
- 712. Minimum ASCII Delete Sum for Two Strings
- Educational Codeforces Round 30 837A. Chores
- [安卓]Android Studio 3.0 安装包说明(2017.10)
- 异常解决:Mapped Statements collection does not contain value for …