Friday, October 25, 2013

Gas Station@leetcode

刷题必备书籍Cracking the Coding Interview: 150 Programming Questions and Solutions 

简历:The Google Resume: How to Prepare for a Career and Land a Job at Apple, Microsoft, Google, or any Top Tech Company
算法学习书籍:Introduction to Algorithms
编程珠玑:Programming Pearls (2nd Edition)
C++ 学习:The C++ Programming Language, 4th Edition
经典操作系统书籍,龙书:Operating System Concepts
创业:The Start-up of You: Adapt to the Future, Invest in Yourself, and Transform Your Career
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.
题没什么难的,就是要注意这是一个circular route, i后面连接的是0,所以index需要处理,而走了多远要用一个额外的变量记录。
刚开始一直time limit exceed,因为我是一个一个station作为start去尝试,后来想其实没必要,因为假如一旦有一个route走不通,我们重新开始的station应该是我们中断的下一个,因为前面的任何一个开始都不会可以,可以证明出来,不细说了,自己想想就可以知道。

1 comment:

  1. 有个问题想请教下
    else
    {
    i=j;
    break;
    }
    这里为什么是i=j; 而不是i=j%gas.size();呢? 谢谢~~

    ReplyDelete

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...