704. 二分查找
思路:代码随想录
这道题目的前提是数组为有序数组,同时题目还强调数组中无重复元素,因为一旦有重复元素,使用二分查找法返回的元素下标可能不是唯一的,这些都是使用二分法的前提条件,当大家看到题目描述满足如上条件的时候,可要想一想是不是可以用二分法了。
细节:
1. while的条件判断
2.right的取值是多少?
class Solution {
public int search(int[] nums, int target) {
// //左闭右闭
// int left = 0, right = nums.length - 1;//注意这边的right取值,因为是左闭右闭
// while (left <= right){
// int mid = (left + right)>>1;
// if (nums[mid] > target){
// right = mid - 1;
// }
// else if (nums[mid] < target){
// left = mid + 1;
// }
// else {
// return mid;
// }
// }
// return -1;
//左闭右开
int left = 0, right = nums.length; //注意这边的right取值,因为是左闭右开
while (left < right) {
int mid = left + ((right - left) >> 1);
if (nums[mid] > target) {
right = mid;
} else if (nums[mid] < target) {
left = mid + 1;
} else {
return mid;
}
}
return -1;
}
}
27.移除元素(简单)
思路:
要知道数组的元素在内存地址中是连续的,不能单独删除数组中的某个元素,只能覆盖。
class Solution {
public int removeElement(int[] nums, int val) {
int slow = 0, fast = 0;
for (; fast < nums.length; fast++){
if (nums[fast] != val){
nums[slow] = nums[fast];
slow++;
}
}
return slow;
}
}
34 在排序数组中查找元素的第一个和最后一个位置
题目链接:. - 力扣(LeetCode)
细节:两次查找
class Solution {
public int[] searchRange(int[] nums, int target) {
//左闭右闭
int left = 0, right = nums.length - 1;
int first = -1, last = -1;
while(left <= right){
int mid = (left + right)>>1;
if (nums[mid] > target){
right = mid - 1;
}
else if (nums[mid] < target){
left = mid + 1;
}
else{
first = mid;
right = mid - 1;
}
}
left = 0;
right = nums.length - 1;
while(left <= right){
int mid = (left + right)>>1;
if (nums[mid] > target){
right = mid - 1;
}
else if (nums[mid] < target){
left = mid + 1;
}
else{
last = mid;
left = mid + 1;
}
}
return new int[]{first,last};
}
}
35 搜索插入位置
细节:想清楚怎么插入这个没有的target
class Solution {
public int searchInsert(int[] nums, int target) {
// //左闭右闭
// int left = 0, right = nums.length - 1;
// while (left <= right){
// int mid = (left + right) >> 1;
// if (nums[mid] > target){
// right = mid - 1;
// }
// else if (nums[mid] < target){
// left = mid + 1;
// }
// else{
// return mid;
// }
// }
// return left;
//左闭右开
int left = 0, right = nums.length;
while (left < right){
int mid = (left + right) >> 1;
if (nums[mid] > target){
right = mid ;
}
else if (nums[mid] < target){
left = mid + 1;
}
else{
return mid;
}
}
return left;
}
}