knakul853

Untitled

Jul 19th, 2020
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.87 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int search(vector<int>& nums, int target) {
  4.        
  5.         int n = (int)nums.size();
  6.          if(n == 0) return -1;
  7.         // find the smallest number.
  8.        
  9.         int l = 0, h = n-1;
  10.        
  11.         while( l < h )
  12.         {
  13.             int mid = (l + ( h -l )/2);
  14.             if(nums[mid] >nums[h]) l = mid + 1;
  15.             else h = mid;
  16.         }
  17.          //cout<<l<<" "<<h<<"\n";
  18.         // faltten the array and use usual binary search.
  19.        int root = l;
  20.         l=0, h=n-1;
  21.        
  22.         while(l <= h)
  23.         {
  24.             int mid = (l + (h - l)/2);
  25.            int midr = mid + root;
  26.             midr = midr % n;
  27.            
  28.             if(nums[midr] == target) return midr;
  29.             if(nums[midr] > target) h = mid - 1;
  30.             else l = mid + 1;
  31.         }
  32.        
  33.         return -1;
  34.        
  35.     }
  36. };
Add Comment
Please, Sign In to add comment