Anyone know what the time complexity would this be?


  • 0
    C
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int remain=0;
        int startingIndex=0;
        int counter=0;
        Set <Integer> mySet=new HashSet<Integer>();
        int i=0;
        do{	i=(startingIndex+counter)%gas.length;
        	remain+=gas[i]-cost[i];
        	if(remain<0){
                startingIndex=++i;
                if(!mySet.add(startingIndex)){
                	return -1;
                }
                counter=0;
                remain=0;
                } else counter++;
        }while(counter<gas.length);
        return startingIndex;
    }
    

    I know this code runs in O(n) space but I'm not sure about the time complexity, is it O(n^2) worst case or for all cases? And how could this code be improved? Thanks~


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.