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.

  • 相关阅读:
    关于javascript中私有作用域的预解释
    javascript中的数据类型
    关于JS面向对象继承问题
    自己写的,js 评分插件
    css的border效果
    css样式表分类
    js DOM的几个常用方法
    js object 对象 属性和方法的使用
    js 函数function的几种形式
    HTML5-新API-geolocation-实例-距离跟踪器
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4856640.html
Copyright © 2011-2022 走看看