My O(logn) C# solution


  • 0
    K
    public int SearchInsert(int[] nums, int target) {
        
        int result = BinarySearch(nums , target);
        
        if(target > nums[nums.Length - 1]) result = nums.Length;
        else if( target < nums[0]) result = 0;
        
        while( result == -1){
            result = BinarySearch(nums , --target);
            if(result != -1)
            {
                result += 1;
                break;
            }
        }
        return result;
    }
    
    public int BinarySearch(int [] nums , int target){
        
        int high = nums.Length - 1;
        int low = 0;
        int index = -1;
        while(low <= high){
            
            int mid = (high + low) / 2;
            
            if(nums[mid] == target)
            {
                index = mid;
                break;
            }
            else if(target > nums[mid]){
                low = mid + 1;
            }
            
            else high = mid - 1;
            
        }
        
        return index;
        
     }

Log in to reply
 

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