[LeetCode][81. Search in Rotated Sorted Array II] The Key of Binary Search Is Narrow the Search Interval
By Long Luo
This article is the solution of Problem 81. Search in Rotated Sorted Array II .
Brute Force
The Brute Force solution is so easy.
Problem 33. Search in Rotated Sorted Array.1
2
3
4
5
6
7
8
9
10public static int search_bf(int[] nums, int target) {
int len = nums.length;
for (int i = 0; i < len; i++) {
if (nums[i] == target) {
return i;
}
}
return -1;
}
Problem 81. Search in Rotated Sorted Array II:1
2
3
4
5
6
7
8
9
10public static boolean search_bf(int[] nums, int target) {
int len = nums.length;
for (int i = 0; i < len; i++) {
if (nums[i] == target) {
return true;
}
}
return false;
}
Analysis
- Time Complexity: \(O(n)\).
- Space Complexity: \(O(1)\).
Binary Search
Step-by-step Binary Search Algorithm:
We basically ignore half of the elements just after one comparison.
- Compare target with the middle element;
- If target matches with the middle element, we return the mid index;
- Else If target is greater than the mid element, then target can only lie in the right half subarray after the mid element. So we recursive for the right half;
- Else (target is smaller) recursive for the left half.
The Key of Binary Search is Narrow the Search Interval, aka reducing the scale of the problem.
Every round exclusive the interval where the target element must not exist, so the scale of the problem is gradually reduced.
Problem 33. Search in Rotated Sorted Array.