您的位置:首页 > 理论基础 > 数据结构算法

数据结构与算法-二分查找

2017-02-17 00:00 561 查看

二分法

二分搜索是一种在有序数组中,寻找目标值得经典方法.使用前提是有序数组. 有的情况需要自己构造有序数组

使用场景

可转换为find the first/last position of..

时间复杂度最少为O(logN).

模板总结

核心: binary search问题转化为:寻找第一个或者最后一个,target元素出现的位置. Find the first/last position of target in numbers.

要素1: 第一步是异常处理

要素2: while 循环条件 start+1<end;防止陷入死循环.

要素3:
mid=start+(end-start)/2;
需要考虑 int overflow问题.

要素4: array[mid]==,>,<在循环中,分三种情况讨论边界;在移动start和end时,单纯移动到mid位置,不要+1或者-1;统一在程序最后写return语句,有利于可读性

要素5: 循环结束后,讨论情况:1. start+1==end 分别讨论start,end与target的关系; 2. start==end 同情况一一样讨论.

[code lang=java] /** * Created by liuhang on 2016/10/28. */ public class binarySearchSolution { public int lowerBound(int[] array, int target) { /** * Find the first position of target */ if (array == null || array.length == 0) return -1; int start = 0, end = array.length - 1; while (start + 1 < end) { int mid = start + (end - start) / 2; if (array[mid] == target) end = mid; if (array[mid] > target) end = mid; if (array[mid] < target) start = mid; } if (array[start] == target)//返回第一个target值,先看start return start; if (array[end] == target) return end; return -1; } public int upperBound(int[] array, int target) { /** * Find the last position of target; */ if (array == null || array.length == 0) return -1; int start = 0, end = array.length - 1; while (start + 1 < end) { int mid = start + (end - start) / 2; if (array[mid] == target) start = mid;//start往前提 if (array[mid] > target) end = mid; if (array[mid] < target) start = mid; } if (array[end] == target)//返回最后一个target return end; if (array[start] == target) return start; return -1; } } [/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: