leetcode第35题C语言解法

我的解法(4ms):

int searchInsert(int* nums, int numsSize, int target) {
    
    int i;
    for( i = 0; i < numsSize; i++ )
    {
        if( nums[i] >= target )
            return i;
    }
    return numsSize;

}

二分查找法(4ms):

int binarySearch(int arr[], int l, int r, int x)
{
    int m;
    while (l <= r)
    {
        m = l + (r-l)/2;
 
   
 
          if ( m == l && m == r)
          {
                  // printf ("%d", m);
            break;
          }
     
        if (arr[m] == x)
            return m;
         
        
     
        if (arr[m] < x)
            l = m + 1;
 

        else
            r = m - 1;
    }
 

   if ( x > arr[m] )
       return m + 1;
    
    else
        return m ;
}

int searchInsert(int* nums, int numsSize ,int target) {
    
    int flag = binarySearch ( nums, 0, numsSize -1 , target);
    return flag;
    
}


你可能感兴趣的:(leetcode第35题C语言解法)