Niuke.com Brushing Questions-Find the target value in the rotated ordered array

Problem Description

Given an ordered array that has been rotated, you don't know how much the array has been rotated in advance.
Search for the given target value in the array, if it can be found in the array, return its index, otherwise return -1.
Assume that there are no duplicates in the array.

Input description:
Input a rotating array

Output description:
the index of the output target value

Example

Example 1

Enter
[3,2,1],1

Output
2

Solutions

analysis

  1. Use deformed binary search.

method

  1. Although the title is given as a rotating array, we can use the dichotomy in the correct interval

Three variables of the dichotomy: start, end, mid.
If arr[mid] <arr[end], it means that mid is in the low interval, and the low interval is looking for the condition of start (the reason for finding the condition of start is that start is moving, indicating that the target is in within the normal range), the movable end of the other conditions are the
conditions CAUSE arr [mid]> = arr [ end], conditions described in the end find a mid range high, the high dynamic range (to find the moving end, the movable end, Explain that the target is in the normal range), the others are all start conditions

Code

// 思路1
public class Solution {
    
      
    public int search(int[] arr, int target) {
    
    
        // write code here
        int start = 0, end = arr.length - 1;
        while (start <= end) {
    
    
            int mid = start + (end - start) / 2;
            if (arr[mid] == target) {
    
    
                return mid;
            } else if (arr[mid] < arr[end]) {
    
    
                if (arr[mid] < target && target <= arr[end]) {
    
    
                    start = mid + 1;
                } else {
    
    
                    end = mid - 1;
                }
            } else {
    
    
                if (arr[start] <= target && target < arr[mid]) {
    
    
                    end = mid - 1;
                } else {
    
    
                    start = mid + 1;
                }
            }
        }

        return -1;
    }
}

Time complexity analysis:
O(logN): Binary search is used, so the time complexity is logN.

Space complexity analysis:
O(1): No extra space is used

If you want to test, you can go directly to the link of Niuke.com to do the test

Find the target value in the rotated ordered array

Guess you like

Origin blog.csdn.net/qq_35398517/article/details/113621460