Title Description
The beginning of an array of several elements moved to the end of the array, the array we call rotation. A non-decreasing input array sort of a rotation, output rotation smallest element array. For example, an array {3,4,5,1,2} {1,2,3,4,5} is a rotation of the array to a minimum. NOTE: All the elements are given in greater than 0, if the array size is 0, return 0.
Problem-solving ideas:
The first method: direct traverse the array, find the minimum value
The second method: dichotomy, use binary search to find the minimum. Three cases to consider: 1, array [mid]> array [high] This situation is similar to array [3,4,5,6,0,1,2], in this case a certain minimum number of mid right. At this time, because the array is incremented so that the minimum value between these two numbers, so that low = mid + 1;
2, array [mid] <array [High] This situation is similar to array [2,2,3,4,5,6,6], then the minimum number of array necessarily [mid] or the left mid, MID = High ;
3、array[mid] == array[high] high = high - 1;
Code:
import java.util.ArrayList;
public class Solution {
public int minNumberInRotateArray(int [] array) {
int len = array.length;
if(len == 0)
return 0;
int low = 0, high = len - 1;
while(low < high){
int mid = low + (high - low) / 2;
if(array[mid] > array[high]){
low = mid + 1;
}else if(array[mid] == array[high]){
high = high - 1;
}else{
high = mid;
}
}
return array[low];
}
}
When I refer here to find someone else's code with a high array.size () - said they would not be given 1:00, to find a method to use to find the vector found
function returns the size of the vector size vector, return type size_type, Member type size_type IS AN unsigned Integral type, i.e. an unsigned integer;
vector<int> A;
A.size () - 1 because the size returned value is an unsigned type so A.size () - 1 out of range, a large number of
Proper use (int) (A.size () - 1), so that a can
ps: Vector class is in java can automatically increase the array of objects ,
-
capacity
It refers to the total number of elements in the container before the allocation of new storage space that can be stored.
-
size
It refers to the number of elements currently stored in the container