一、LeetCode 704 二分查找
题目链接:704.二分查找
解法一:左闭右闭
class Solution {public int search(int[] nums, int target) {int left = 0, right = nums.length-1;while(left <= right){ //边界处理,左闭右闭int mid = left + (right-left)/2;if(nums[mid] < target){ //target在右,左指针后移left = mid+1;}else if(nums[mid] > target){ //target在左,右指针前移right = mid-1;}else{return mid;}}return -1;}
}
解法二:左闭右开
class Solution {public int search(int[] nums, int target) {int left = 0, right = nums.length;while(left < right){ //边界处理,左闭右开int mid = left + (right-left)/2;if(nums[mid] < target){ //target在右,左指针后移left = mid+1;}else if(nums[mid] > target){ //target在左,右指针前移right = mid;}else{return mid;}}return -1;}
}
扩展题目
35.搜索插入位置
思路:利用二分法找到插入位置:若存在,返回下标;若不存在,退出while循环,返回下标left(left = right+1)。
代码如下:
class Solution {public int searchInsert(int[] nums, int target) {int left = 0, right = nums.length-1;while(left <= right){int mid = left + (right-left)/2;if(nums[mid] < target){left = mid+1;}else if(nums[mid] > target){right = mid-1;}else{return mid;}}return left;// left = right+1}
}
34.在排序数组中查找第一个和最后一个元素的位置
思路:排序数组-可以使用二分。利用二分法找到任意该元素的位置;向左和向右找到边界位置。
代码:
class Solution {public int[] searchRange(int[] nums, int target) {int left = 0, right = nums.length-1;int[] ans = new int[2];int mid = 0;//先使用二分法找到target值while(left <= right){mid = left + (right-left)/2;if(nums[mid] < target){left = mid+1;}else if(nums[mid] > target){right = mid-1;}else{break;}}//确定起始点和终点if(left > right){ans[0] = -1;ans[1] = -1;}else{int index = mid;while(index >= 0 && nums[index] == target){index--;}ans[0] = index+1; //返回下标index = mid;while(index < nums.length && nums[index] == target){index++;}ans[1] = index-1;}return ans;}
}
二、LeetCode 27 移除元素
题目链接:27.移除元素
思路:设置双指针,一次遍历过程中将指定元素替换到新的数组长度之外。
class Solution {public int removeElement(int[] nums, int val) {int n = nums.length;int left = 0, right = n-1;//双指针遍历while(left <= right){if(nums[left] == val){int temp = nums[left];nums[left] = nums[right];nums[right] = temp;left--; //回溯right--;}left++;}return right+1;}
}
三、今日小结
在感冒中开启刷题的第一天,其实这些题目之前刷过很多遍了,就像英语单词书中的abandon。22年就买了卡哥的代码随想录,刷到一半因为各种事情导致半途而废,2024报名参加了卡哥的算法训练营,希望能一直坚持下去并有所提升,在支离破碎的考研梦中拾到春招的光。