您现在的位置是:首页 >技术杂谈 >算法记录|day1二分查找 + 快慢指针网站首页技术杂谈
算法记录|day1二分查找 + 快慢指针
简介算法记录|day1二分查找 + 快慢指针
二分查找 Bineary Search
入门题 Introduction question
leetcode 704
Given an array of integers nums which is sorted in ascending order,
and an integer target, write a function to search target in nums.
If target exists, then return its index. Otherwise, return -1.
You must write an algorithm with O(log n) runtime complexity.
这里采用的是开区间
左闭右开
[ left, right)
[0, nums.length)
分别是三个判断
There are three judgments
nums[mid]
等于target 直接返回 Equal to target and returns directly
大于target 更新左边界greater than target —>Update left boundary
小于target 更新有边界 less than target —> Updates with boundaries
感悟
就是 不断地缩小边界
constantly narrowing the boundaries
每次缩小一半
Reduce by half each time
时间复杂度为log(n)
The time complexity is log (n)
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) {
return mid;
} else if (nums[mid] > target) {
right = mid;
} else {
left = mid + 1;
}
}
return -1;
}
}
链接
https://leetcode.com/problems/binary-search/
fast and slow pointers 快慢指针
leetcode 27
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.
Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:
Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.
Return k.
Custom Judge:
The judge will test your solution with the following code:
解法
先写暴力
使用一个 while 循环遍历 nums
发现 元素 等于 val 就 删除
删除是通过一个新的循环,将 i 之后 所有元素往前移动一位
删除完之后, i -= 1 n -= 1
当前位置就无了,所以往前退一个
总大小 n 也减少一个
class Solution {
public int removeElement(int[] nums, int val) {
int i = 0;
int n = nums.length;
while (i < n) {
if (nums[i] == val) {
for (int j = i + 1; j < nums.length; j++) {
nums[j - 1] = nums[j];
}
// when nums[i] = val
// delete cur nums[i]
// therefore the i -= 1
// the whole size - 1
i -= 1;
n -= 1;
}
i += 1; // move i forward
}
return n;
}
}
再写快慢
使用两个指针循环遍历数组
快指针遍历,发现 不等于val的数字
赋值给慢指针,然后慢指针移动一下
直到快指针遍历完成
class Solution {
public int removeElement(int[] nums, int val) {
int fast = 0, slow = 0;
while (fast != nums.length) {
if (nums[fast] != val) {
nums[slow] = nums[fast];
slow++;
}
fast++;
}
return slow;
}
}
链接
https://leetcode.com/problems/remove-element/
风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。