This article is a basket of original stools
Article Original address: http://www.cnblogs.com/dbylk/p/4032570.html
Original question:
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.
Explain:
Suppose an ordered array has been rotated to an unknown axis in advance,
(for example 0 1 2 4 5 6 7
, after rotation 4 5 6 7 0 1 2
),
Find the smallest value in the rotated array,
It is assumed that duplicate data does not exist in the array.
Ideas:
- Because the original array is ordered, the first element of the rotated array must be greater than the last element,
- If the above conditions are not met, indicating that the array is not rotated or the position of the axis of rotation is 0, you can directly return the first element as an answer.
- After the array is truncated from the middle, the smallest value in the original array is still the smallest value in the array after the second half of the array is discarded.
- Based on the above three conditions, we can find the smallest element in the array using the dichotomy method:
① uses the head variable to mark the position of the first element of the array, tail the position of the tail element of the two fractional groups.
② Num[head] > Num[tail], then proceed to step ③, otherwise the array satisfies the condition 1, at this time Num[head] is the decimal number to be asked.
③ uses the Med to mark the middle element position of the array.
④ num[med] > Num[head], indicating that the left half of the array is ordered, the rotation point must be in the right half, so that head = Med, continue to perform step ②.
⑤ num[med] < Num[head], indicating that the left half of the array is unordered, the rotation point must be in the left half of the paragraph, so tail = med, continue to perform step ②.
⑥ if num[med] = Num[head], indicating that there are only two or one element in the array (there are no duplicate elements in the array), the rotation point must be the minimum value in Num[head] and num[tail, so the minimum value is returned at this time.
Source:
classSolution { Public: intFindmin (vector<int> &num) { intSize =num.size (); if(!size) { return 0; } intHead =0; inttail = size-1; while(Head <=tail) { if(Num[head] >Num[tail]) { intMed = head + tail >>1; if(Num[med] >Num[head]) {Head=Med; } Else if(Num[med] <Num[head]) {Tail=Med; } Else { returnNum[head] < Num[tail]?Num[head]: Num[tail]; } } Else { returnNum[head]; } } return 0; }};
"Leetcode" Find Minimum in rotated Sorted array finds the smallest value in an ordered array after rotation