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.

  • 相关阅读:
    java.lang.NoClassDefFoundError: org/springframework/dao/support/DaoSupport
    project configuration is not up-to-date with pom.xml
    消息列队5
    消息列队4
    消息列队3
    聊聊常见的数据库架构设计方案?
    消息队列2
    消息队列1
    搜索引擎5
    搜索引擎4
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4856640.html
Copyright © 2011-2022 走看看