博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Binary Search
阅读量:5239 次
发布时间:2019-06-14

本文共 1896 字,大约阅读时间需要 6 分钟。

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 , 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.

 

转载于:https://www.cnblogs.com/ireneyanglan/p/4856640.html

你可能感兴趣的文章
C# 之 提高WebService性能大数据量网络传输处理
查看>>
md5sum命令详解
查看>>
[bzoj1004] [HNOI2008] Cards
查看>>
应该是实例化对象的没有对属性赋值时,自动赋值为null,但不是空指针对象引用...
查看>>
原生HttpClient详细使用示例
查看>>
几道面试题
查看>>
Factory Design Pattern
查看>>
python中贪婪与非贪婪
查看>>
guava API整理
查看>>
无锁编程笔记
查看>>
jquery mobile
查看>>
如何在vue单页应用中使用百度地图
查看>>
Springboot使用步骤
查看>>
Spring属性注入
查看>>
Springboot-配置文件
查看>>
Springboot-日志框架
查看>>
SpringBoot-thymeleaf
查看>>
P1192-台阶问题
查看>>
一、使用pip安装Python包
查看>>
spring与quartz整合
查看>>