153. Find Minimum in Rotated Sorted Array

每日一题 2019 - 05 - 15


题目:

Suppose an array sorted in ascending order 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.

Example 1:

1
2
Input: [3,4,5,1,2] 
Output: 1

Example 2:

1
2
Input: [4,5,6,7,0,1,2]
Output: 0

解法:

这个题让在给定翻转的数组中找到最小元素,直接使用从头到尾遍历的方法就可以解决问题,但是既然给出了部分有序数组,那就一定是在考察二分查找了,所以这个题也可以使用二分查找解决问题;

由于是部分数组有序,所以每次找的时候从中间开始找,拿着当前l r 下的中间的元素跟数组的头元素对比,如果中间元素大于头元素,把 l 置为 mid,否则把 r 置为 mid ,直到r - l == 1,即可完成任务;


代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public:
int findMin(vector<int>& nums) {
if(nums[nums.size()-1] > nums[0] || nums.size() == 1)
{
return nums[0] ;
}
if(nums.empty())
{
return 0 ;
}
int l = 0 ;
int r = nums.size() - 1 ;
while(1)
{
if(r - l == 1)
{
return nums[r];
}
int mid = ( l + r ) / 2 ;
if(nums[mid] >= nums[0])
{
l = mid ;
}
else
{
r = mid ;
}
}
}
};
0%
undefined