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,
    每天早上叫醒你的不是闹钟,而是心中的梦~
  • 相关阅读:
    谷粒商城Day1
    解决GitHub访问慢的问题
    Java基础知识面试题
    Spring框架学习
    MATLAB基础学习(3)——数值数组及运算
    MATLAB基础学习(2)
    MATLAB基础学习篇(1)
    页面加载之前显示正在加载
    CSS设置多余的文本显示省略号
    Node.js(六)- HTTP知识先填坑
  • 原文地址:https://www.cnblogs.com/vintion/p/4116878.html
Copyright © 2011-2022 走看看