LeetCode - Find Minimum in Rotated Sorted Array

Find Minimum in Rotated Sorted Array

2015.1.22 07:07

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

Find the minimum element.

You may assume no duplicate exists in the array.

Solution:

  With no duplicates in the array, you'll find it easy to perform binary search on that position of the minimal element. Please see the code below for yourself.

  Total time complexity is O(log(n)). Space complexity is O(1).

Accepted code:

 1 // 1AC, typical problem

 2 class Solution {

 3 public:

 4     int findMin(vector<int> &num) {

 5         int n = (int)num.size();

 6         

 7         if (num[0] < num[n - 1]) {

 8             return num[0];

 9         }

10         

11         int ll, mm, rr;

12         

13         ll = 0;

14         rr = n - 1;

15         while (rr - ll > 1) {

16             mm = ll + (rr - ll) / 2;

17             if (num[mm] > num[ll]) {

18                 ll = mm;

19             } else {

20                 rr = mm;

21             }

22         }

23         

24         return num[rr];

25     }

26 };

 

你可能感兴趣的:(LeetCode)