C++ binary search.


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

Log in to reply
 

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