首页 > 代码库 > LeetCode - Find Minimum in Rotated Sorted Array
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 - Find Minimum in Rotated Sorted Array
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。