# 9.1二分查找（Binary Search）

#### First Occurrence

a = 1, 2, 3 }，t＝2，返回1
a = { 1, 2, 3 }，t＝4，返回- 1
a = { 1, 2, 2，2, 3 }，t＝2，返回1

``````public class Solution {
public int firstOccur(int[] arr, int target) {
if(arr==null||arr.length==0)return-1;
int left = 0;
int right = arr.length-1;
while(left<right-1){
int mid = left+(right-left)/2;
if(arr[mid]<target){
left = mid;
}else{
right = mid;
}
}

if(arr[left]==target){
return left;
}
if(arr[right]==target){
return right;
}
return -1;
}
}
//物理意义：
//left < target <= right
``````

#### Last Occurrence

``````public class Solution {
public int lastOccur(int[] arr, int target) {
if(arr == null || arr.length==0)return -1;
int left = 0;
int right = arr.length-1;
while(left<right-1){
int mid = left+(right-left)/2;
if(arr[mid]<=target){
left = mid;
}else{
right = mid;
}
}
if(arr[right] == target)return right;
if(arr[left] == target)return left;
return -1;
}
}
//物理意义：
//left <= target < right
``````

#### Closest In Sorted Array, 找到最接近target的index

Given a target integer T and an integer array A sorted in ascending order, find the index i in A such that A[i] is closest to T.
Assumptions:
There can be duplicate elements in the array, and we can return any of the indices with same value.
Examples:
A = {1, 2, 3}, T = 2, return 1
A = {1, 4, 6}, T = 3, return 1
A = {1, 4, 6}, T = 5, return 1 or 2
A = {1, 3, 3, 4}, T = 2, return 0 or 1 or 2

``````public class Solution {
public int closest(int[] arr, int target) {
if(arr==null||arr.length==0)return -1;
int left = 0;
int right = arr.length-1;
while(left < right-1){
int mid = left+(right-left)/2;
if(arr[mid]==target)return mid;
if(arr[mid]<target){
left = mid;
}else{
right = mid;
}
}
int abs1 = Math.abs(arr[left]-target);
int abs2 = Math.abs(arr[right]-target);
return abs1>abs2?right:left;
}
}
//物理意义：
//left <= target <= right
``````

#### Search In Sorted Matrix I

``````public class Solution {
public int[] search(int[][] matrix, int target) {
int[] res = {-1,-1};
int left = 0;
int m = matrix.length;
int n = matrix[0].length;
int right = m*n-1;
while(left<=right){
int mid = left+(right-left)/2;
if(matrix[mid/n][mid%n] == target){
res[0] = mid/n;
res[1] = mid%n;
return res;
}
if(target<matrix[mid/n][mid%n]){
right = mid-1;
}else{
left = mid+1;
}
}

return res;
}
}
``````

#### K Closest In Sorted Array

Given a target integer T, a non-negative integer K and an integer array A sorted in ascending order, find the K closest numbers to T in A.
Assumptions
A is not null
K is guranteed to be >= 0 and K is guranteed to be <= A.length
Return
A size K integer array containing the K closest numbers(not indices) in A, sorted in ascending order by the difference between the number and T.
Examples
A = {1, 2, 3}, T = 2, K = 3, return {2, 1, 3} or {2, 3, 1}
A = {1, 4, 6, 8}, T = 3, K = 3, return {4, 1, 6}

``````public class Solution {
//time:O(lgn+k); space:O(k);
public int[] kClosest(int[] arr, int target, int k) {
if(arr == null || arr.length == 0){
return arr;
}
if( k == 0 ){
return new int[0];
}
int[] result = new int[k];
int left = largestSmallerEqual(arr, target);
int right = left + 1;
for(int i=0; i<k; i++){//O(k)
if(right>=arr.length || left>=0 && target-arr[left]<=arr[right]-target){
result[i] = arr[left--];
}else{
result[i] = arr[right++];
}
}

return result;
}

//O(lgn)
private int largestSmallerEqual(int[] arr, int target){
int left = 0;
int right = arr.length-1;
while ( left<right-1 ){//left<=target<right
int mid = left+(right-left)/2;
if(arr[mid]<=target){
left = mid;
}else{
right = mid;
}
}
if(arr[right]<=target){
return right;
}

if(arr[left]<=target){
return left;
}

return -1;
}
}
``````

### 推荐阅读更多精彩内容

• "use strict";function _classCallCheck(e,t){if(!(e instanc...
久些阅读 1,494评论 0 1
• pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类： pyspark.sql...
mpro阅读 8,089评论 0 11
• mean to add the formatted="false" attribute?.[ 46% 47325/...
ProZoom阅读 1,534评论 0 3
• ——四面八方的座椅翻涌，一个浪潮险些要将他吞没。 春分刚过，花热热闹闹地开了一地，空气也跟着花变得一样芬芳，带点葱...
平稚晖阅读 82评论 0 0
• 咏梅 北风怔怔朱花起，料峭山头独自开。 试问凛然谁与比？凌峰悬月退高台。
旧稔阅读 284评论 8 19