Cpp Solution Binary Search O(logN)


  • 0
    S
    class Solution {
    public:
        int util(vector<int>& nums, int target, int low, int high){
            if(low>high){
                return low;
            }
            int mid = (low+high)/2;
            if(nums[mid] == target){
                return mid;
            }
            if(mid<high && (nums[mid] < target && nums[mid + 1] > target )){
                return mid+1;
            }
            if(mid>low && (nums[mid-1] < target && nums[mid] > target)){
                return mid;
            }
            if(nums[mid] < target){
                return util(nums,target,mid+1,high);
            }else{
                return util(nums,target,low,mid-1);
            }
        }
        int searchInsert(vector<int>& nums, int target) {
            int n = nums.size();
            return util(nums,target,0,n-1);
        }
    };

Log in to reply
 

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