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.

  • 相关阅读:
    基于遗传算法(Genetic Algorithm)的TSP问题求解(C)
    分治思想:合并排序和快速排序
    冒泡排序和选择排序
    WPF线程
    DataGrid属性和事件
    WPF限制TextBox只能输入数字
    键盘键值对应表
    转换人民币大小金额
    查找DataGrid某个单元格中的控件
    WPF中DataGrid使用初步
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4856640.html
Copyright © 2011-2022 走看看