二分法
左闭右闭
public int search(int[] nums, int target) {
int left=0;
int right=nums.length-1;
while(right>=left){
int mid=(right-left)/2+left;
if(nums[mid]>target){
right=mid-1;
}else if(nums[mid]<target){
left=mid+1;
}else{
return mid;
}
}
return -1;
}
对于半开区间,如左闭右开,while判断中是left<right,因为==无意义。当nums[mid]>target时,right=mid。因为right是开的
对于在排序数组中查找元素的第一个和最后一个位置
class Solution {
public int[] searchRange(int[] nums, int target) {
int leftBorder=getLeftBorder(nums,target);
int rightBorder=getRightBorder(nums,target);
if(leftBorder==-2||rightBorder==-2)return new int[]{-1,-1};
if(rightBorder-leftBorder>1)return new int[]{leftBorder+1,rightBorder-1};
else return new int[]{-1,-1};
}
public int getLeftBorder(int[] nums, int target){
int left=0;
int right=nums.length-1;
int leftBorder=-2;
while(left<=right){
int mid=left+(right-left)/2;
if(nums[mid]>=target){
right=mid-1;
leftBorder=right;
}else{
left=mid+1;
}
}
return leftBorder;
}
public int getRightBorder(int[] nums, int target){
int left=0;
int right=nums.length-1;
int rightBorder=-2;
while(left<=right){
int mid=left+(right-left)/2;
if(nums[mid]>target){
right=mid-1;
}else{
left=mid+1;
rightBorder=left;
}
}
return rightBorder;
}
}
移除元素
快慢指针的方法
class Solution {
public int removeElement(int[] nums, int val) {
int fast=0;
int slow=0;
while(fast<nums.length){
if(nums[fast]!=val){
nums[slow]=nums[fast];
slow++;
}
fast++;
}
return slow;
}
}