Sorted Insert Position

 

Given a sorted array A and a target value B, 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.

 

int searchInsert(vector<int> &A, int target) {
            int n = A.size();
            int start = 0, end = n - 1;
            int mid;
            while(start <= end){
                mid = (start + end) / 2;
                if(target == A[mid]){
                    return mid;
                }
                else if(target < A[mid]){
                    end = mid - 1;
                }
                else{
                    start = mid + 1;
                }
            }
            return start;
        }

 

Comments

Popular posts from this blog

Perfect Peak of Array

Is Rectangle?

Sort array with squares!