Rotate the smallest number of the array-sword refers to offer

Title description:

Rotate the smallest number of the array

Moving the first few elements of an array to the end of the array is called the rotation of the array.
Input a rotation of a non-decreasing sorted array, and output the smallest element of the rotated array.
NOTE: All elements given are greater than 0, if the array size is 0, please return 0.

Example 1:
Input: [3,4,5,1,2]
Return value: 1

Example 2:
Input: [1,1,1,0,1]
Output: 0

answer:

Method 1: Violent method:
traverse the array directly to find the minimum value. But the additional conditions of this question are useless. It's definitely not the answer the interviewer expected.

Method 2: Binary search
This binary search is difficult, arr[mid] compares with whom.
Our purpose is: When a comparison is made, it must be determined that the answer is on one side of mid. A comparison is a question of whom arr[mid] compares with.
The general comparison principle is:
if there is a target value target, then directly compare arr[mid] with target.
If there is no target value, the endpoint can generally be considered.
Here we regard target as the right endpoint for analysis. Then we need to analyze the following three situations to see if the above goal can be achieved.

Case 1: arr[mid]> arr[right]: 4 5 6 1 2 3
arr[mid] is 6, arr[right] is 3, arr[mid]> arr[right], indicating that [left… mid] is all It is >= arr[right], because the original array is non-decreasing, so it can be determined that the answer is [mid+1...right] interval, so left = mid + 1

Case 2: arr[mid] <arr[right]: 5 6 1 2 3 4
arr[mid] is 1, arr[right] is 4, arr[mid] <arr[right], indicating that the answer is definitely not in [mid+ 1…right], but arr[mid] may be the answer, so the answer is in the range of [right, mid], so right = mid;

Case 3: arr[mid] == arr[right]:
if it is 1 0 1 1 1, arr[mid] = arr[right] = 1, obviously the answer is on the left
if it is 1 1 1 0 1, arr[mid] = arr[right]= 1, Obviously the answer is on the right.
So in this case, it is not sure whether the answer is on the left or the right, so let right =right-1; slowly narrow the interval without missing the answer.

Code:

/**
 * 
 * @param rotateArray int整型一维数组 
 * @param rotateArrayLen int rotateArray数组长度
 * @return int整型
 */
int minNumberInRotateArray(int* rotateArray, int rotateArrayLen ) {
    
    
    // write code here
    int left =0;
    int right = rotateArrayLen-1;
    int mid;
    if(rotateArrayLen==0)
        return 0;
    while(left < right)
    {
    
    
         mid = left + ((right-left)>>1);
       if(rotateArray[mid] > rotateArray[right]){
    
    
           left = mid + 1;
       }else if(rotateArray[mid] < rotateArray[right]){
    
    
           right = mid;
       }else{
    
    
           right--;
       }
    }
    return rotateArray[left];
}

Guess you like

Origin blog.csdn.net/weixin_50843868/article/details/110100494