Search Insert Position @LeetCode

PROBLEM :

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Here are few examples.
[1,3,5,6], 5 -> 2
[1,3,5,6], 2 -> 1
[1,3,5,6], 7 -> 4
[1,3,5,6], 0 -> 0

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION : O(n) Solution
--------------------------------------------------------------------------------

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        if(nums.size()==0)
            return 0 ;
           
        int pos=0 ;
        for(int i=0;i<nums.size();i++){
            if(nums[i]>target)
                return pos ;
               
            if(nums[i]==target)
                return i ;
               
            pos++ ;
        }
        return pos ;
    }
};

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION : O(logn) Solution
--------------------------------------------------------------------------------

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

--------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )