解题思路:判断区间范围:[ ] or [ )
情况一:左闭右闭区间 => right = num.length - 1
循环条件为while(left <= right),如果target < num[mid], right = mid - 1
理解:以[1,1]举例, 1 <= 1 是成立的
代码如下:
class Solution{
public int search(int[] nums, int target) {
int l = 0;
int r = nums.length - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (target < nums[mid]) {
r = mid - 1; //下一次搜索区间为[l, mid - 1]
} else if (nums[mid] < target) {
l = mid + 1;
} else {
return mid;
}
}
return -1; //l > r,未找到目标值
}
}
情况二:左闭右开区间 => right = num.length
循环条件为while(left < right),如果target < num[mid],right = mid
代码如下:
class Solution{
public int search(int[] nums, int target) {
int l = 0;
int r = nums.length;
while (l < r) {
int mid = (l + r) / 2;
if (target < nums[mid]) {
r = mid; //下一次搜索区间为[l, mid) 即 [l, mid - 1]
} else if (nums[mid] < target) {
l = mid + 1;
} else {
return mid;
}
}
return -1;
}
}
解题思路:运用快慢指针使时间复杂度为O(n)
快指针:对旧数组的每个元素进行遍历,查找新数组所需元素
慢指针:指向需要更新的元素下标
代码如下:
class Solution{
public int removeElements(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;
}
}
今日心得
之前学习过二分查找的,但是写代码时又忘记了,有点不清楚return的用法,递归还是有点昏。学会了快慢指针的思想,nice!第一次写博客,不太熟练~
积少成多,功不唐捐