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.

  • 相关阅读:
    Mysql创建nextval函数
    宝塔配置tomcat的配置
    小程序获取授权信息
    pycharm 2017新建文件添加编码方式等
    Linux下利用expect,不用交互模式,直接登陆远程主机
    linux文件权限解析(摘)
    linux环境下根据文件的某一列进行去重
    oracle查询用户权限及角色(摘)
    插入排序-python实现
    css清除浮动方法
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4856640.html
Copyright © 2011-2022 走看看