704.二分查找
https://leetcode.cn/problems/binary-search/description/
一、左闭右闭
`//左闭右闭
public static int erFen1(int[] nums,int target){
if (target < nums[0] || target > nums[nums.length-1]){
return -1;
}
int maxIndex = nums.length-1;
int minIndex = 0;
int index = (minIndex + maxIndex)/2;
while (minIndex <= maxIndex){
if (nums[index] == target){
return index;
}else {
if (target > nums[index]){
minIndex = index + 1;
}else {
maxIndex = index - 1;
}
index = (minIndex + maxIndex)/2;
}
}
return -1;
}`
二、左闭右开
`//左闭右开
if (target < nums[0] || target > nums[nums.length-1]){
return -1;
}
int maxIndex = nums.length;
int minIndex = 0;
while (minIndex < maxIndex){
int index = minIndex + ((maxIndex - minIndex) >> 1);
if (nums[index] == target){
return index;
}else {
if (target > nums[index]){
minIndex = index + 1;
}else {
maxIndex = index;
}
}
}
return -1;
}`
总结:很简单的题目,关键点在于左闭右闭的while判断条件是<= 而左闭右开的while判断条件时< 左闭右开因为<=没有意义
27. 移除元素
https://leetcode.cn/problems/remove-element/description/
public static int removeElement(int[] nums, int val) {
int slow = 0;
for (int fast = 0; fast < nums.length; fast++) {
if (nums[fast] != val){
nums[slow] = nums[fast];
slow++;
}
}
return slow;
}
总结:快慢指针即可 slow不仅是慢指针,同时也携带了新数组的长度信息
标签:minIndex,index,27,target,nums,int,随想录,maxIndex,移除 From: https://www.cnblogs.com/jeasonGo/p/18055971