# Leetcode Binary search二分法算法相关题的java实现和解析(第一篇）

• Binary search(First position)
• Binary search(Last postion)
• Search and insert position
• Find minimum in rotated sorted array
• Find the first and last element

## Binary search(First position)

class Solution{
public int binarySearch(int[] nums, int target){
if(nums == null || nums.length == 0)return 0;
int start = 0, end = nums.length-1;
while(start + 1 < end){
int mid = (end-start)/2 + start;
if(nums[mid] >= target) end = mid;
else{
start = mid;
}
}
if(nums[start] == target) return start;
if(nums[end] == target) return end;
return -1;
}
}


## Binary search(Last postion)

class Solution{
public int BinarySearch(int[] nums, int target){
if(nums == null || nums.length == 0)return 0;
int start = 0, end = nums.length-1;
while(start+ 1 < end){
int mid = (end-start)/2 +start;
if(nums[mid] <= target) start = mid;
else[
end = mid;
}
}
if(nums[end] == target) return end;
if(nusm[start] == target) return start;
return -1;
}
}


## Search insert position

class solution{
public int searchInsert(int[] nums,int target){
if(nums == null || nums.length == 0)return 0;
int start = 0, end = nums.length-1;
if(nums[start] > target) return start;
if(nums[end] < target) return end+1;
while(start +1 < end){
int mid = (end-start)/2 + start;
if(nums[mid] < target)start = mid;
else{
end = mid;
}
}
if(nums[start] == target)return start;
return end;
}
}


## Find minimum in rotated sorted array

class Solution{
public int minRSA(int[] nums)[
if(nums == null|| nums.length == 0)return 0;
int start = 0, end = nums.length -1;
int target = nums[end];
while(start + 1 < end){
int mid = (end-start)/2 + start;
if(nums[mid] <= target)end = mid;
else{
start = mid;
}
}
if(nums[start] <= target) return start;
return end;
}
}


## Find the first and last element

class Solution {
public int[] searchRange(int[] nums, int target) {
int[] res = new int[2];
if(nums == null || nums.length == 0){
res[0] = -1;
res[1] = -1;
return res;
}
int first = helper(nums,target,true);
if(first == nums.length || nums[first] != target){
res[0] = -1;
res[1] = -1;
return res;
}
res[0] = first;
res[1] = helper(nums,target,false);
return res;
}
protected int helper(int[] nums,int target,boolean first){
int start = 0, end = nums.length-1;
while(start + 1 < end){
int mid = (end-start)/2+start;
if(first){
if(nums[mid] >= target)end = mid;
else{start = mid;}
}else{
if(nums[mid] <= target) start = mid;
else{end = mid;}
}
}
if(first){
if(nums[start] == target) return start;
return end;
}
else{
if(nums[end] == target) return end;
return start;
}
}
}


public class Solution extends VersionControl {
int start = 0,end = n;

while(start + 1 < end){
int mid = (end-start)/2 + start;
start = mid;
}else{
end = mid;
}
}
return end;
}
return start;
}
return end;
}
}


08-28 1万+

07-23 756
02-24 202
03-22 1956
03-10 920
09-24 167
05-13 2942
08-30 1871
09-29 5663
04-03 417