Topic:
Suppose a sorted array is rotated on 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.
Assume no duplicate exists in the array.
Idea: ① The most primitive traversal of the array is good; ② binary search can reduce the complexity of the algorithm.
C + + code one (walk through the array data honestly):
class Solution{public: int findMin(vector<int> &num) { for1; i < num.size(); i++) { if1return num[i]; } return num[0]; }};
C + + code two (two-point lookup):
classsolution{ Public:intFindmin ( vector<int>&num) {size_t size = num.size ()-1;intleft =0;intright =int(size);intMiddle = right/2;//Note here that the loop condition has an equal sign while(left <= right) {middle = (left+ right)/2;//If the middle is larger than the last digit, the minimum value is on the right and vice versa, the minimum value is on the left if(Num[middle] > num[size]) left = middle +1;Elseright = Middle-1; }returnNum[left]; }};
C + + code three (for middle and two different):
classsolution{ Public:intFindmin ( vector<int>&num) {size_t size = num.size ()-1;intleft =0;intright =int(size);intMiddle = right/2; while(left <= right) {middle = left + (right-left)/2;if(Num[middle] > num[size]) left = middle +1;Elseright = Middle-1; }returnNum[left]; }};
C + + code four (right is different from two, note that while loop condition will also be different):
classsolution{ Public:intFindmin ( vector<int>&num) {size_t size = num.size ()-1;intleft =0;intright =int(size);intMiddle = right/2;//here loop condition without equal sign while(Left < right) {middle = (right + left)/2;if(Num[middle] > num[size]) left = middle +1;Elseright = Middle; }returnNum[left]; }};
C # code:
Public classsolution{ Public intFindmin (int[] num) {intsize = num. Length-1;int Left=0;int Right= size;intMiddle = Right/2; while( Left< Right) {middle = ( Left+ Right) /2;if(Num[middle] > Num[size]) Left= Middle +1;Else Right= Middle; } return num[ Right]; }}
Python code:
Class Solution:# @param num, a list of integers # @return An integerdef findmin (self,Num): size =Len(Num) -1left =0 Right= SizeMiddle= Right/2 whileLeft < Right:Middle= (left + Right) /2 if Num[Middle] >Num[size]: left =Middle+1 Else: Right=Middle return Num[Left]
Leetcode:find Minimum in rotated Sorted Array