Binary Search (Tree) + Bisection - Algorithm


Binary search
- Prefer [], start=0, end=len-1
- int mid = left + (right - left) / 2;
- if low

  1. public int searchRightIndex(int[] nums, int left, int right, int target) {  
  2.     while (left <= right) {  
  3.         int mid = (left + right) / 2;  
  4.         if (nums[mid] > target) right = mid - 1;  
  5.         else left = mid + 1;  
  6.     }  
  7.     return right;  
  8. }  
  9. public int searchLeftIndex(int[] nums, int left, int right, int target) {  
  10.     while (left <= right) {  
  11.         int mid = (left + right) / 2;  
  12.         if (nums[mid] < target) left = mid + 1;  
  13.         else right = mid - 1;  
  14.     }  
  15.     return left;  
  16. }  

LeetCode 35 - Search Insert Position
LeetCode 34 - Search for a Range
find the starting and ending position of a given target value.
start = Solution.firstGreaterEqual(A, target);
end = firstGreaterEqual(A, target + 1) - 1;

LeetCode 278 - First Bad Version
http://www.cnblogs.com/anne-vista/p/4848945.html

LeetCode 374 - Guess Number Higher or Lower
https://leetcode.com/articles/guess-number-higher-or-lower/

X. Search in rotated sort array
LeetCode 153 - Find the minimum element in a sorted and rotated array

LeetCode 33 - Searching an Element in a Rotated Sorted Array
    public int search(int[] nums, int target) {
        int start = 0;
        int end = nums.length - 1;
        while (start <= end){
            int mid = (start + end) / 2;
            if (nums[mid] == target)
                return mid;
        
            if (nums[start] <= nums[mid]){// can be just < as no duplicate
                 if (target < nums[mid] && target >= nums[start]) 
                    end = mid - 1;
                 else
                    start = mid + 1;
            } 
        
            if (nums[mid] <= nums[end]){//<
                if (target > nums[mid] && target <= nums[end])
                    start = mid + 1;
                 else
                    end = mid - 1;
            }
        }
        return -1;
    }
LeetCode 81 - Search in Rotated Sorted Array II


Bisection
- Suppose we know the answer, it's easier to determine whether the answer is true/possible
- isPossible(**, int curValue)

LeetCode 287 - Find the Duplicate Number
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive),
- Constant space, don't modify the array
- Bisection (1, nums.length-1)
- 32(n)
public int findDuplicate(int[] nums) {
    int n = nums.length-1, res = 0;
    for (int p = 0; p < 32; ++ p) {
        int bit = (1 << p), a = 0, b = 0;
        for (int i = 0; i <= n; ++ i) {
            if (i > 0 && (i & bit) > 0) ++a;
            if ((nums[i] & bit) > 0) ++b;
        }
        if (b > a) res += bit;
    }
    return res;
}
- O(n) find cycle in LinkedList


find the contiguous subarray whose length is greater than or equal to k that has the maximum average value.
        for (int n: nums) {
            max_val = Math.max(max_val, n);
            min_val = Math.min(min_val, n);
        }
        double prev_mid = max_val, error = Integer.MAX_VALUE;
        while (error > 0.00001) {
            double mid = (max_val + min_val) * 0.5;
            if (check(nums, mid, k))
                min_val = mid;
            else
                max_val = mid;
            error = Math.abs(prev_mid - mid);
            prev_mid = mid;
        }

You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins.
Given n, find the total number of full staircase rows that can be formed.

LeetCode 410 - Split Array Largest Sum
you can split the array into m non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these m subarrays.
- TODO DP

LintCode - Copy Books
Return the number of smallest minutes need to copy all the books.
- DP
- Bisection O(nlg(sum/k)), (max, total)

- sizeIsDoable (1, Math.min(height, width))
            while (minSize <= maxSize) {
                // The font size that will be attempted
                int currentTargetSize = (minSize + maxSize) / 2;

                // See if the given font size fits
                if (sizeIsDoable(currentTargetSize, width, height, message)) {
                    // It fits, save as largest so far and try even larger
                    minSize = currentTargetSize + 1;
                    bestSize = currentTargetSize;
                } else {
                    // Doesn't fit, try smaller sizes
                    maxSize = currentTargetSize - 1;
                }
            }

Compute the integer/real square root

LeetCode 367 - Valid Perfect Square
- O(nlogn) Bisection (1, num/2)

Codeforces Round #318 - Bear and Elections

POJ 3104 -- Drying
Poj 3258 - River Hopscotch
POJ 3273 -- Monthly Expense
POJ 3122 - Pie

X. Binary Search tree/TreeMap/TreeSet
- [lower, upper bound]
- In order traversal, prev node
- Binary search tree: TreeSet, window size k
- Use TreeSet or TreeMap directly
- Or can't when need store extra info in node such as sameCount, leftCount

LeetCode 530 - Minimum Absolute Difference in BST
- In order traversal, prevNode
- [lower, upper bound]

LeetCode - 220 Contains Duplicate III
find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
- Bucket sort
- Binary search tree: TreeSet, window size k O(nlogk)

LeetCode 352 - Data Stream as Disjoint Intervals
- TreeMap intervals to merge interval based on start
- TreeSet

LeetCode 436 - Find Right Interval
- Use TreeMap to store intervals
- Use TreeMap> to handle duplicate start
- Sort Intervals based on start + binary search

LeetCode 493 - Reverse Pairs
we call (i, j) an important reverse pair if i < j and nums[i] > 2*nums[j].
- Build the Binary Search Tree from right to left
- Merge Sort

LeetCode 414 - Third Maximum Number
Use PriorityQueue with HashSet to check duplicate
https://discuss.leetcode.com/topic/63086/java-priorityqueue-o-n-o-1
TreeSet (not PQ as need call contains)
set.add(num);
if(set.size() > 3) {set.remove(set.first());}
Maitain state: first, second, third

Labels

adsense (5) Algorithm (69) Algorithm Series (35) Android (7) ANT (6) bat (8) Big Data (7) Blogger (14) Bugs (6) Cache (5) Chrome (19) Code Example (29) Code Quality (7) Coding Skills (5) Database (7) Debug (16) Design (5) Dev Tips (63) Eclipse (32) Git (5) Google (33) Guava (7) How to (9) Http Client (8) IDE (7) Interview (88) J2EE (13) J2SE (49) Java (186) JavaScript (27) JSON (7) Learning code (9) Lesson Learned (6) Linux (26) Lucene-Solr (112) Mac (10) Maven (8) Network (9) Nutch2 (18) Performance (9) PowerShell (11) Problem Solving (11) Programmer Skills (6) regex (5) Scala (6) Security (9) Soft Skills (38) Spring (22) System Design (11) Testing (7) Text Mining (14) Tips (17) Tools (24) Troubleshooting (29) UIMA (9) Web Development (19) Windows (21) xml (5)