knakul853

Untitled

Jun 26th, 2020
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.20 KB | None | 0 0
  1. /**
  2. knakul853
  3. **/
  4. class Solution {
  5. public:
  6.     vector<int> searchRange(vector<int>& nums, int target) {
  7.        
  8.         vector<int>ans;
  9.         ans.push_back(lower_bound(nums, target));
  10.         ans.push_back(upper_bound(nums, target));
  11.        
  12.         return ans;
  13.        
  14.     }
  15.     int lower_bound(vector<int>& nums, int t)
  16.     {
  17.         int l=0, r=(int)nums.size()-1;
  18.         int ans = -1;
  19.         while(l<=r)
  20.         {
  21.             int mid = l + ( r - l )/2;
  22.            
  23.             if(nums[mid] == t)
  24.             {
  25.                 ans = mid;
  26.             }
  27.            
  28.             if(nums[mid] >= t){
  29.                 r = mid - 1;
  30.             }
  31.             else l = mid + 1;
  32.         }
  33.        
  34.         return ans;
  35.     }
  36.       int upper_bound(vector<int>& nums, int t)
  37.     {
  38.         int l=0, r=(int)nums.size()-1;
  39.         int ans = -1;
  40.         while(l<=r)
  41.         {
  42.             int mid = l + ( r - l )/2;
  43.            
  44.             if(nums[mid] == t)
  45.             {
  46.                 ans = mid;
  47.             }
  48.            
  49.             if(nums[mid] > t){
  50.                 r = mid - 1;
  51.             }
  52.             else l = mid + 1;
  53.         }
  54.        
  55.         return ans;
  56.     }
  57. };
Add Comment
Please, Sign In to add comment