zoukankan      html  css  js  c++  java
  • Binary Search

    Time complexity O(log(n)). When the question requires O(log(n)) time complexity, we always need to think whether it can be solved by binary search.

    For binary search, there are several key elements to consider:

    1. when to stop while loop?

    2. how to change start pointer?

    3. how to change end pointer?

    4. is it required to find first/ last/ any position of target?

    5. use iterative or recursive way, which is better?

    According to template provide by Jiuzhang, we concludes a general way to implement binary sort.

     1 class Solution {
     2     /**
     3      * @param nums: The integer array.
     4      * @param target: Target to find.
     5      * @return: The first position of target. Position starts from 0.
     6      */
     7     public int binarySearch(int[] nums, int target) {
     8         if (nums == null || nums.length == 0) {
     9             return -1;
    10         }
    11         
    12         int start = 0, end = nums.length - 1;
    13         while (start + 1 < end) {
    14             int mid = start + (end - start) / 2;
    15             if (nums[mid] == target) {
    16                 end = mid;  
    17             } else if (nums[mid] < target) {
    18                 start = mid;
    19             } else {
    20                 end = mid;
    21             }
    22         }
    23         if (nums[start] == target) {
    24             return start;
    25         }
    26         if (nums[end] == target) {
    27             return end;
    28         }
    29         return -1;
    30     }
    31 }

    From the template, we noticed that:

    1. Each time, we set start = mid or end = mid to avoid index out of range.

    2. Stop criterion is a. target is found b. start + 1 = end (i.e start and end are adjacent points).

    In second situation, we need to check both start and end pointers.

    If it's required to return first position --> first check start, then check end.

    If it's required to return last position --> first check end, then check start.

  • 相关阅读:
    PCA手写版 Learner
    泛解析和伪静态实现二级域名(net技术)
    内存分配笔记(一)
    NVelocity的使用总结
    从discuz 里扒过来的一个通用序列化和反序列化类
    类中的执行顺序
    Nhibernate 工具 Nh profiler 使用方法
    UML中几种类间关系
    golf的23种设计模式
    net中的定时器
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4856640.html
Copyright © 2011-2022 走看看