Binary search

in a **sorted array**

Two types:

  • shrink, have upper and lower bound

  • expand, as a multiplication

Shrinkage Template

https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/description/

class Solution {
    public int findMin(int[] nums) {
        // Corner case
        if (nums.length == 0) return -1;
        if (nums.length == 1) return nums[0];
        if (nums[0] < nums[nums.length -1]) return nums[0];

        // Narrow the range
        // Key: 1) left + 1 < right 2) right = mid;left = mid;
        while (left + 1 < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] < nums[mid-1]) return nums[mid];
            if (nums[mid] > nums[0]) {
                left = mid;
            } else if (nums[mid] < nums[0]) {
                right = mid;
            } else {
                if (nums[mid] <= nums[left]){
                    left++;
                } else {
                    right--;
                }
            }
        }

        // Determine left and right   
        if (nums[left] < nums[right]) {
            return nums[left];
        } else {
            return nums[right];
        }
    }
}

Option 1: left <= right, left = mid + 1, right = mid - 1 Option 2: stop at left and right point, then compare 2 points. left + 1 < right, right = mid;left = mid;

Expand Template

https://leetcode.com/problems/powx-n/description/

Binary Serarch in Matrix

similar idea:

while (left + 1e-6 < right) https://leetcode.com/problems/minimize-max-distance-to-gas-station/description/ https://leetcode.com/problems/k-th-smallest-prime-fraction https://leetcode.com/problems/maximum-average-subarray-ii/description/

Last updated

Was this helpful?