返回
81. Search in Rotated Sorted Array II
前端
2023-12-20 10:16:31
## Understanding the Problem
The problem provides an array `'num'` which is "rotated." A rotated array means it's a **sorted** array, but the elements have been shuffled so that the beginning of the array doesn't contain the minimum value.
**Example:**
- [4, 5, 6, 7, 0, 1, 2, 3] is a rotated version of [0, 1, 2, 3, 4, 5, 6, 7].
- The minimum value in the original (unrotated) array is located at index 0. In the rotated version, it's located at index 4.
## Solution using Binary Search
We'll solve this problem using a modified version of Binary Search. The reason we need to change the original Binary Search is because we can't assume that the middle element is always greater than the left or smaller than the right. This is because the array is rotated.
### The steps of the modified Binary Search are as follows:
1. Check if the `'low'` is less than or equal to `'high'`, which means there are still elements to search.
2. Find the middle index `'mid'`, as we do in the original Binary Search.
3. Check if the value at `'mid'` is equal to the target value. If it is, return `'true'` because we found the target.
4. Check if the left half of the array is **sorted** . If it is, we can do a normal Binary Search on the left half.
5. If the left half is not **sorted** , it means we might have found a **rotated** part of the array. In this case, we can't tell for sure if the target is in the left or right half. We'll have to search both.
### Time and Space Analysis
The time and space complexities of this solution are both `O(logN)`, where `N` is the length of the input array.
## Sample Test Cases
- Input: `'num = [4, 5, 6, 7, 0, 1, 2, 3]', 'target = 2'`
- Expected output: `true`
- Input: `'num = [4, 5, 6, 7, 0, 1, 2, 3]', 'target = 8'`
- Expected output: `false`
## Follow-up Question
- What if there are duplicate elements in the array?
- If the array may contain duplicate elements, the solution becomes slightly more complex. In this case, we can't simply assume that we can do a normal Binary Search on the left or right half. We'll have to check if the elements on the left or right side are different.