[Leetcode] Find Minimum in rotated Sorted Array

Source: Internet
Author: User

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] :

    1. 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 ;
    2. 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.