Binary Search
For a given sorted array (ascending order) and a target number, find the first index of this number in O(log n) time complexity.
If the target number does not exist in the array, return -1.
Example:
If the array is [1, 2, 3, 3, 4, 5, 10], for given target 3, return 2.
1 | class Solution { |
Key Points:
while(start < end)
: when start and end are overlapped each other, break. At this moment, we can return start or end. But it is different when we need to return the index before or after the target(see point 3).int mid = start + (end - start) / 2
: in order to avoid overflow ofstart + end
, we need to do a little trick here.while loop
: in the while loop, there are two different needs:
- return the index of the target: as the example above.
- return the one before(example below)/after the target:
Search Insert PositionHere, we need to use1
2
3
4
5
6
7
8
9
10while(start <= end) {
int mid = start + (end - start) / 2;
if(A[mid] == target) {
return mid;
} else if(A[mid] < target) {
start = mid + 1;
} else {
end = mid - 1;
}
}while(start <= end)
so that when we break the loop, two pointers are at two different(but neighbored) positions. Besides, if we want to return the one before the index, we returnstart
, otherwise we returnend
.
Example: Search in rotated sorted array:
In line 15, we can’t use A[mid] < A[right]
, eg: [3,1,1], 3.
1 | while(left <= right) { |
Similar Problems:
Search for a Range:
When finding left position, if mid == target
, move end
so that when break the loop, start
will be like: [end, start(left-most one)])
.
Similarly, when finding right position, if mid == target
, move start
, so that end
will be like: [end(right-most one), start]
when break.
Search in rotated sorted array II: worst case will cost O(n) time
Find minimum in rotated sorted array
Find minimum in rotated sorted array II
Search a 2D matrix
Search a 2D matrix II: from top-right to bottom-left, so that left element is always smaller.
Find a peak:
1 | if(A[mid] < A[mid + 1]) { |
Sorted Array
Using Swap:
Given a rotated sorted array, recover it to sorted array in-place.
- Reverse the left part of the pivot
- Reverse the right part of the pivot
- Reverse the whole array
eg.
[4, 5, 1, 2, 3] -> [5, 4, 1, 2, 3] -> [5, 4, 3, 2, 1] -> [1, 2, 3, 4, 5]
Similar Problems:
Rotate String
Reverse words in a string
Find Top k:
Median of two sorted arrays:
General top-k problem. In this code, k
is not the index, but the kth top number. So when we use k
in an array, we need to -1
.
1 | public class Solution { |
Similar Problems:
Remove dulplicates from sorted array
Remove dulplicates from sorted array II
Merge sorted array
Merge sorted array II
Comments