My straight forward C# solution -- Accepted


  • 0
    N
    public int SearchInsert(int[] nums, int target) {
       
       if(nums.Length ==0)
        return 0;
        
        if(target > nums[nums.Length-1])
        return nums.Length;
        
        if (target < nums[0])
        return 0;
       
       return BinarySearch(nums , target,0,nums.Length);
    }
    public int BinarySearch(int[]nums , int target , int min,int max)
    {
        while(min <= max)
        {
            int mid = (min+max)/2;
            if(target == nums[mid])
            return mid;
            
            if(target<nums[mid])
            max = mid-1;
            
            else if(target > nums[mid])
            min = mid+1;
        }
        if(target > nums[min])
        return min+1;
        else 
        return min;
    }

Log in to reply
 

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