Find the minimum value of the number of rotations in C language daily question

Hello, today we share a topic, which is a topic on Niuke.com

Find the minimum value in the rotation array https://www.nowcoder.com/practice/9f3231a991af4f55b95579b44b7a01ba?tpId=13&tqId=23269&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

Then let's take a look at the meaning of the title first. First, we must understand
insert image description here
what the title is about. This, but don't misunderstand that it is out of order, and out of order is random numbers.
There are two solutions to this question. One is that we compare the past one by one from the front to the back, first define a min = the first item, and then assign the value to min if it is smaller than it. Everyone will know this, so today we will talk about it. Let me write to you with the idea of ​​binary search

Binary search is an ordered array. When we want to find the position of a number, we take the middle number for comparison. For example, if there is an ascending array, we take the middle number and compare it with the value we want. If it is greater than the middle number, it means that this number is behind the middle number, then we take the number after the middle number to the middle number of the last number, and compare them. After we find the number in this way, we can quickly find it s position

Then we can use this idea to analyze this problem

  1. The middle is greater than the right [3, 4, 5, 1, 2], in this case, the smallest number must be on the right; then left = middle + 1
  2. The middle is equal to the right side [1, 0, 1, 1, 1], this is rotated from [0, 1, 1, 1, 1], at this time need to narrow the range right–;, note that it cannot be left++, because it is a non-descending
    array , so it is necessary to narrow the range on the right and push the smaller value to the right, which is in line with our judgment rules.
  3. The middle is smaller than the right [5, 1, 2, 3, 4], in this case, the smallest number is on the left half; then right = middle
int minNumberInRotateArray(int* rotateArray, int rotateArrayLen ) {
    
    
if (rotateArrayLen == 0) return 0;
int left = 0, right = rotateArrayLen - 1, mid;
if (rotateArray[right] > rotateArray[left]) return rotateArray[0];
while(left < right) {
    
    
mid = left + (right - left) / 2;
if (rotateArray[mid] > rotateArray[right]) left=mid+1;
//中间的数大,那么我们就要往mid后面找,说明最小值在mid后面
//而且保证mid不是最小数,因为right有更小的数
else if (rotateArray[mid] == rotateArray[right]) right--;
//如果是这样的旋转数{0,1,1,1,1,1,1}
else right = mid;//中间的数小,那我们就要往右边找,而且这个中间数也可以是最小的数,所以不能写成right=mid-1
}
return rotateArray[left];//因为只有right=left的时候while循环条件不满足,那么才会退出循环,所以这里写right也对
}

That's all for today's sharing, let's work hard together

Guess you like

Origin blog.csdn.net/2301_76895050/article/details/131627780