本文共 825 字,大约阅读时间需要 2 分钟。
思路:
依旧借用二叉搜索的方法,使用rank()函数。题目假设没有重复数字,可以肯定的是,循环结束是因为while条件不满足。此时必定有,将nums[i]>key不成立,在此前,nums[i]>key是一定成立的。
所以 i 是,像 “4 5 6 7”这样序列后移一位的下标,如果是序列是升序,没有翻转,i会会越界,注意判断。
if(nums[mid]>key) i=mid+1;
题目:
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.
class Solution {public: int findMin(vector & nums) { int len=nums.size(); if(len==1) return nums[0]; int key=nums[0]; int i=1; int j=len-1; int mid; while(i<=j) { mid=(j-i)/2+i; if(nums[mid]>key) i=mid+1; else j=mid-1; } if(i>=len) return nums[0]; //防止没有翻转 return nums[i]; } };
转载地址:http://yxwtb.baihongyu.com/