Simple C++ solution using BinarySearch in O(log(n)) Time Complexity


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

Log in to reply
 

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