每日一题 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 | Input: [3,4,5,1,2] |
Example 2:
1 | Input: [4,5,6,7,0,1,2] |
解法:
这个题让在给定翻转的数组中找到最小元素,直接使用从头到尾遍历的方法就可以解决问题,但是既然给出了部分有序数组,那就一定是在考察二分查找了,所以这个题也可以使用二分查找解决问题;
由于是部分数组有序,所以每次找的时候从中间开始找,拿着当前l
r
下的中间的元素跟数组的头元素对比,如果中间元素大于头元素,把 l
置为 mid
,否则把 r
置为 mid
,直到r - l == 1
,即可完成任务;
代码:
1 | class Solution { |