首页 > 其他 > 详细

LeetCode - Find Minimum in Rotated Sorted Array

时间:2015-01-22 08:13:15      阅读:254      评论:0      收藏:0      [点我收藏+]

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 - Find Minimum in Rotated Sorted Array

原文:http://www.cnblogs.com/zhuli19901106/p/4240610.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!