Question 1:
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.
Question 2: If the array that is allowed on the question has duplicate numbers?
Solution: The most stupid method, but also the easiest way to think of is to directly traverse the array, find the minimum value, time complexity O (n), but for the subject obviously will time out. At this point, it is easy to think of binary search, because it is orderly. But there must be something different about the two.
The code for the first question is as follows:
public int findmin (int[] num) { int low = 0; int high = num.length-1; while (Low < high-1) { int mid = low + (high-low)/2; if (Num[low] < Num[high]) { if (Num[mid] < Num[low]) {Low = Mid, } else {high = mid; } } else { if (Num[mid] < Num[high]) {High = Mid, } else {low = mid; }}} return Num[low] > Num[high]? Num[high]: Num[low]; }
This question must be distinguished, whether the sequence is incremented or decremented. Many methods of solving the problem have not been considered. Obviously has the first question the thought, the second question also is good solution.
public int findmin (int[] num) { int low = 0; int high = num.length-1; while (Low < high-1) { int mid = low + (high-low)/2; if (Num[low] < Num[high]) { if (Num[mid] < Num[low]) {low = mid; } else if (Num[mid] > Num[low]) {
high = mid; } else { low++; } } else { if (Num[mid] < Num[high]) {High = mid; } else if (Num[mid] > Num[high]) {low = mid; } else { high--; } } } return Num[low] > Num[high]? Num[high]: Num[low]; }
Leetcode-find Minimum in rotated Sorted array (find the smallest value in the inverse array)