Advertisement
vaibhav1906

Search Insert Position

Nov 24th, 2021
1,504
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.58 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int searchInsert(vector<int>& nums, int target) {
  4.        
  5.         int n = nums.size();
  6.        
  7.         int l = 0;
  8.         int h = n-1;
  9.         //To find the first true for the condition nums[m]>=target
  10.         while(l<h){
  11.            
  12.             int m = l + (h-l)/2;
  13.            
  14.             if(nums[m]>= target){
  15.                 h = m;
  16.             }
  17.             else{
  18.                 l = m+1;
  19.             }
  20.            
  21.         }
  22.        
  23.         if(target>nums[n-1])return n;
  24.        
  25.         return l;
  26.        
  27.        
  28.     }
  29. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement