zoukankan      html  css  js  c++  java
  • leetcode-gas station

    Gas Station

     Total Accepted: 12395 Total Submissions: 50855My Submissions

    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.

    Have you been asked this question in an interview? 

    最开始的方法,超时了:
    class Solution {
    public:
        int canCompleteCircuit(vector<int> &gas, vector<int> &cost)
        {
            int len = gas.size();
            int tank ;
            int start,i;
            for(start=0;start<len;start++)
            {
                tank = 0;
                 for(i=0;i<len;i++)
                {
                    if(i+start<len)
                    {
                        tank += gas[i+start];
                        tank -= cost[i+start];
                        if(tank<0)break;
                    }
                    else
                    {
                        tank += gas[i+start-len];
                        tank -= cost[i+start-len];
                        if(tank<0)break;
                    }
                        
                }
                if(i!=len)continue;
                else
                    break;
            }
            if(start==len)return -1;
            return start;       
        }
    };

    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
            // Note: The Solution object is instantiated only once.
    		int total = 0;
    		int currentgas = 0; 
    		int startpoint = -1;
    		int sz = gas.size();
    		for(int i = 0; i < sz; i++)
    		{
    			currentgas += gas[i] - cost[i];
    			total += gas[i] - cost[i];
    			if(currentgas < 0)
    			{
    				startpoint = i;
    				currentgas = 0;
    			}
    		}
    		return total >= 0 ? startpoint+1 : -1;
        }

    解题报告:
    当然,这题如是一个一个开始,然后把所有点走一遍,再判断是否成立,这个是可以的,也是最正常的思维,但复杂度O(n2)
    这就是第一种解法
    不得不优化。
    有如下规律,如果一串数字,总和大于等于0,则必存在某一点,从这点开始,一真累加,每次都是非负数
    这样,我们只需要判断最后的结果是否为非负就知道是否存在解,即total>=0
    要找到开始的那个点,就判断是否是一直>=0,
    每天早上叫醒你的不是闹钟,而是心中的梦~
  • 相关阅读:
    jvm基本结构和解析
    多态的意思
    java中对象的简单解读
    double类型和int类型的区别
    python 解析xml文件
    win10不能映射Ubuntu共享文件
    Qt程序打包
    Ubuntu boot分区文件误删,系统无法启动,怎么解
    ubuntu Boot空间不够问题“The volume boot has only 5.1MB disk space remaining”
    Ubuntu 分辨率更改 xrandr Failed to get size of gamma for output default
  • 原文地址:https://www.cnblogs.com/vintion/p/4116878.html
Copyright © 2011-2022 走看看