General

start < end

  • [start, end), end 為開區間

  • while退出條件為 target < start = end

public int binarySearch(int[] arr, int target){
    int start = 0; end = arr.length;  // [start, end)
    // target <= start = right
    while(start < end){
        int mid = start + (end - start)/2;
        if(mid > target) end = mid;
        else if (mid < target) start = mid+1;
        else return mid;
    }

    // 返回target 前一個 index
    return start;
}

start + 1 < end

  • while 直到 [[start][end]]相鄰退出,

  • if duplicate, 會在頭兩個的位置

  • find last element of target, if (nums[mid] == target) start = mid

34 Find First and Last Position of Element in Sorted Array

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

Your algorithm's runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

74 find element in a 2-D array

[[1,2,3] [4,5,6] [7,8,9]]

240 find element in a 2-D array ll

Find a occurrence of given number in a 2-D array

[[1,2,3 [2,3,4] [3,4,5]]

  • Search from bottom left to top right

  • each row is sorted, start new search y index from row + 1

702 Search in a big sorted array with unknown size

Given an integer array sorted in ascending order, write a function to search target in nums. If target exists, then return its index, otherwise return -1. However, the array size is unknown to you. You may only access the array using an ArrayReader interface, where ArrayReader.get(k) returns the element of the array at index k (0-indexed).

Search the insert position

  • One more scenario to define [1,2,3], target = 4

  • Use target to define return position

Count of smaller number

  • Sort A first

  • Not include the target number => similar to "insertion position"

658. Find K closest Elements

Given a sorted array, two integers k and x, find the k closest elements to x in the array.

  • A[i] to A[i+k-1]

  • Binary search, 利用 x 與兩邊的距離

  • x = 3, k =2 [1,1,2,2,2,2,2,3,3], 需特別處理 兩邊到x距離相等的情況

Last updated