Binary Search

Useful toturial:

  • https://leetcode.com/discuss/general-discussion/786126/python-powerful-ultimate-binary-search-template-solved-many-problems

  • https://www.zhihu.com/question/36132386/answer/530313852

Search in Rotated Sorted Array

Link: https://leetcode.com/problems/search-in-rotated-sorted-array/

Code:

class Solution {
    public int findRotateIndex(int[] nums) {
        int n = nums.length;
        int left = 0, right = n - 1;
        if (left == right) return 0;
        if (nums[right] >= nums[left]) return 0;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] > nums[mid + 1]) return mid + 1;
            if (nums[mid - 1] > nums[mid]) return mid;
            if (nums[0] < nums[mid]) left = mid;
            if (nums[0] > nums[mid]) right = mid;
        }
        return -1;
    }
    
    public int search(int[] nums, int target) {
        int n = nums.length;
        
        // nums length is 1.
        if (n == 1) {
            if (nums[0] == target) return 0;
            if (nums[0] != target) return -1;
        }
        
        // pivot index
        int k = findRotateIndex(nums);
        
        // initialize left and right index.
        int left, right;
        if (k == 0) {
            left = 0;
            right = n - 1;
        } else if (nums[0] <= target) {
            left = 0;
            right = k - 1;
        } else {
            left = k;
            right = n - 1;
        }
        // binary search
        int mid;
        while (left <= right) {
            mid = left + (right - left) / 2; 
            if (nums[mid] == target) return mid;
            if (nums[mid] < target) left = mid + 1;
            if (nums[mid] > target) right = mid - 1;
        }
        return -1;
    }
}

First Bad Version

Link: https://leetcode.com/problems/first-bad-version/

Code:

Sqrt(x)

Link: https://leetcode.com/problems/sqrtx/

Code:

  • Special case: x = 0, x = 1;

  • mid * mid may overflow, so use long.

  • after exiting the while loop, left is the minimal k​ satisfying the condition

Search Insert Position

Link: https://leetcode.com/problems/search-insert-position/

Code:

Capacity To Ship Packages Within D Days

Link: https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/

Code:

Last updated