Performance of keyword break in Javascript


  • 0
    F
    var searchInsert = function(nums, target) {
        
        if(nums.length === 0){
            return -1;
        }
        
        var greaterThanPrev = false;
        
        for(var i = 0; i < nums.length; i++){
            if(nums[i] === target){
                return i;
            }else if(nums[i] < target){
                greaterThanPrev = true;   
            }else{
                if(greaterThanPrev){
                    return i;
                }
            }
        }
            
        if(!greaterThanPrev){
            return 0
        }else{
            return nums.length
        }
    };
    

    Time complexity of this method should be O(n)
    This is my first try, then I am thinking to add a break when the target is smaller than next element.

    var searchInsert = function(nums, target) {
        if(nums.length === 0){
            return -1;
        }
        
        var greaterThanPrev = false;
        
        for(var i = 0; i < nums.length; i++){
            if(nums[i] === target){
                return i;
            }else if(nums[i] < target){
                greaterThanPrev = true;   
            }else{
                if(greaterThanPrev){
                    return i;
                }else{
                    break;
                }
            }
        }
            
        if(!greaterThanPrev){
            return 0
        }else{
            return nums.length
        }
        
        
    };
    

    Time complexity of second method should be o(logn).
    But time for first method is always like 95 ms, while the second is 125 ms.
    Anyone has idea on this?


Log in to reply
 

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