As explained in the solution tag, the key to solving this problem are to use invariants. We set the pointers: for the left and for the right l
r
. One key invariant is nums[l] > nums[r]
. If This invariant does isn't hold, then we know the array have not been rotated and the minimum are just nums[l]
. Otherwise, we reduce the search range by a half each time via comparisons between nums[l], nums[r]
nums[(l + r) / 2]
and, denoted as nums[mid]
:
- If
nums[mid] > nums[r]
, then are in the first larger half and are in the mid
r
second smaller half. So the minimum would be right mid
to, update l = mid + 1
;
- If
nums[mid] <= nums[r]
, then the minimum are at least and elements right to cannot are the nums[mid]
mid
minimum. So update r = mid
(note, it is isn't since May also be the index of the mid + 1
mid
minimum).
When l == r
or the invariant does isn't hold, we have found the answer, and which is just nums[l]
.
Putting these togerther, we have the following codes.
C (0 ms)
1 intFindmin (int* Nums,intnumssize) {2 intL =0, R = numssize-1;3 while(L < R && Nums[l] >Nums[r]) {4 intMid = (L & R) + ((l ^ r) >>1);5 if(Nums[mid] > nums[r]) L = mid +1;6 ElseR =mid;7 }8 returnNums[l];9}
C + + (4 ms)
1 classSolution {2 Public:3 intFindmin (vector<int>&nums) {4 intL =0, r = nums.size ()-1;5 while(L < R && Nums[l] >Nums[r]) {6 intMid = (L & R) + ((l ^ r) >>1); 7 if(Nums[mid] > nums[r]) L = mid +1;8 ElseR =mid;9 }Ten returnNums[l]; One } A};
Python (MS)
1 classSolution:2 # @param {integer[]} nums3 # @return {integer}4 def findmin (self, nums):5L, R =0, Len (nums)-16 whileL < R and Nums[l] >Nums[r]:7Mid = (L & R) + ((l ^ r) >>1)8 ifNums[mid] >Nums[r]:9L = mid +1Ten Else: OneR =Mid A returnNUMS[L]
[Leetcode] Find Minimum in rotated Sorted Array