LeetCode June Challenge - Day 10

Problem: LeetCode June Challenge - Day 10

Ideas:

  1. Binary search for O(log(n)) complexity.

Solution:

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