Search rotation sorted array of binary search deformation

Title: LeetCode (33)

Suppose an array sorted in ascending order is rotated at a certain point unknown in advance.
(For example, the array [0,1,2,4,5,6,7] may become [4,5,6,7,0,1,2]).
Search for a given target value, if the target value exists in the array, return its index, otherwise return -1.
You can assume that there are no duplicate elements in the array.
The time complexity of your algorithm must be O(log n) level.
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2 ], target = 3
Output: -1

Problem solution:
The meaning of the problem is to let us search for a given value in the rotating array, if it exists, return the corresponding coordinate of this value, if it does not exist, return -1 directly. After careful consideration, we will find that it is actually a variant of binary search. Consider binary search. But the difficulty of this question is that we don’t know where the original array is rotated. We still use the example given in the title to analyze. The array [0 1 2 4 5 6 7] has the following seven rotation methods:

[0 1 2 4 5 6 7] 
[7 0 1 2 4 5 6] 
[6 7 0 1 2 4 5] 
[5 6 7 0 1 2 4] 
[4 5 6 7 0 1 2] 
[2 4 5 6 7 0 1] 
[1 2 4 5 6 7 0] 

Observation results: when the median value is greater than the rightmost value, the left side is in order; when the median value is less than the rightmost value, the right side is in order. So we only need to use the first and last two arrays in the ordered half to judge whether the target value is in this area, so that we can determine which half to keep.

int rotatedBinarySearch(int[] arr, int target){
    
    
 	// 最左侧元素下标
 	int left = 0;
 	// 最右侧元素下标
 	int right = arr.length - 1;
 	while(left <= right){
    
    
 	// 中间元素下标
 	int mid = left + (right - left) / 2;
 	if(arr[mid] == target){
    
    
 		return mid;
	 }
 
 // 情况1:如果中间元素在旋转点左侧
 	if(arr[mid] >= arr[left]){
    
    
 //target 如果位于中间元素的左侧
	 if(arr[mid] > target && target >= arr[left]){
    
    
 		right = mid - 1;
 	}else{
    
    
 	left = mid + 1;
 	      }
	 }
 // 情况2:中间元素在旋转点的右侧
 	else{
    
    
 // target 如果位于中间元素的右侧
	 if(arr[mid] < target && target <= arr[right]){
    
    
	 	left = mid + 1;
 	}else{
    
    
 		right = mid - 1;
 	     }
 	}
	 }
 	return -1; 
 	}

Guess you like

Origin blog.csdn.net/qq_43078445/article/details/106962381