第四天
声明:本系列文章仅适合二刷有经验的算法er学习,以后会出详细的每一题的讲解,这里只是简单的说明思路来帮助大家快速刷完Top101,另外博主的算法全程跟着 labuladong 大佬学习,这里特此声明
45.滑动窗口的最大值
解题思路
- 维护一个双端队列,先遍历一个窗口,加入第一个值,通过while循环去掉比自己先进队列但是值小于自己的节点
- 遍历后续数组元素,此时双端队列头结点即为滑动窗口的最大值,继而通过 while 循环弹出窗口移走后的值
代码实现
public class Solution {
public ArrayList<Integer> maxInWindows(int [] num, int size) {
ArrayList<Integer> res = new ArrayList<Integer>();
//窗口大于数组长度的时候,返回空
if(size <= num.length && size != 0){
//双向队列
ArrayDeque <Integer> dq = new ArrayDeque<Integer>();
//先遍历一个窗口
for(int i = 0; i < size; i++){
//去掉比自己先进队列的小于自己的值
while(!dq.isEmpty() && num[dq.peekLast()] < num[i])
dq.pollLast();
dq.add(i);
}
//遍历后续数组元素
for(int i = size; i < num.length; i++){
//取窗口内的最大值
res.add(num[dq.peekFirst()]);
while(!dq.isEmpty() && dq.peekFirst() < (i - size + 1))
//弹出窗口移走后的值
dq.pollFirst();
//加入新的值前,去掉比自己先进队列的小于自己的值
while(!dq.isEmpty() && num[dq.peekLast()] < num[i])
dq.pollLast();
dq.add(i);
}
res.add(num[dq.pollFirst()]);
}
return res;
}
}
46.最小K个数
解题思路
维护一个最大堆,先往堆中加入K个元素,如果后续数组中的元素值小于堆顶元素的值,让堆顶元素弹出,加入此较小的元素
代码实现
public class Solution {
public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) {
ArrayList<Integer> res = new ArrayList<>();
if (k == 0 || input.length == 0) {
return res;
}
//大根堆
PriorityQueue<Integer> q = new PriorityQueue<>((o1, o2) -> o2.compareTo(o1));
for (int i = 0; i < k; i++) {
q.offer(input[i]);
}
for (int i = k; i < input.length; i++) {
//较小的元素入堆,弹出较大的元素
if (q.peek() > input[i]) {
q.poll();
q.offer(input[i]);
}
}
for (int i = 0; i < k; i++) {
res.add(q.poll());
}
return res;
}
}
47.寻找第K大
解题思路
通过快速排序的方式来进行寻找,经典题,建议背诵
代码实现
public class Solution {
public int findKth(int[] a, int n, int K) {
// write code here
shuffle(a);
int lo = 0, hi = a.length - 1;
K = a.length - K;
while (lo <= hi) {
int p = partition(a, lo, hi);
if (p < K) {
lo = p + 1;
} else if (p > K) {
hi = p - 1;
} else {
return a[p];
}
}
return -1;
}
public int partition(int[] nums, int lo, int hi) {
int pivot = nums[lo];
// 关于区间的边界控制需格外小心,稍有不慎就会出错
// 我这里把 i, j 定义为开区间,同时定义:
// [lo, i) <= pivot;(j, hi] > pivot
// 之后都要正确维护这个边界区间的定义
int i = lo + 1, j = hi;
while (i <= j) {
while (i < hi && nums[i] <= pivot) {
i++;
}
while (j > lo && nums[j] > pivot) {
j--;
}
// 此时 [lo, i) <= pivot && (j, hi] > pivot
if (i >= j) {
break;
}
swap(nums, i, j);
}
swap(nums, lo, j);
return j;
}
public void shuffle(int[] nums) {
Random rand = new Random();
int n = nums.length;
for (int i = 0; i < n; i++) {
int r = i + rand.nextInt(n - i);
swap(nums, i, r);
}
}
public void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
48.数据流中的中位数
解题思路
由于数组大小不确定,因此每次新加入一个元素就进行一次排序时间复杂度很高,这里可以使用插入排序的思路进行
代码实现
public class Solution {
ArrayList<Integer> val = new ArrayList<>();
public void Insert(Integer num) {
if (val.isEmpty()) {
val.add(num);
} else {
int i = 0;
for (; i < val.size(); i++) {
if (num <= val.get(i)) {
break;
}
}
val.add(i, num);
}
}
public Double GetMedian() {
int n = val.size();
if (n % 2 == 1) {
return (double) val.get(n / 2);
} else {
double a = val.get(n / 2);
double b = val.get(n / 2 - 1);
return (a + b) / 2;
}
}
}
49.表达式求值
解题思路
对于「任何表达式」而言,我们都使用两个栈 nums
和 ops
:
nums
: 存放所有的数字ops
:存放所有的数字以外的操作
然后从前往后做,对遍历到的字符做分情况讨论:
- 空格 : 跳过
(
: 直接加入ops
中,等待与之匹配的)
)
: 使用现有的nums
和ops
进行计算,直到遇到左边最近的一个左括号为止,计算结果放到nums
- 数字 : 从当前位置开始继续往后取,将整一个连续数字整体取出,加入
nums
+ - *
: 需要将操作放入ops
中。在放入之前先把栈内可以算的都算掉(只有「栈内运算符」比「当前运算符」优先级高/同等,才进行运算),使用现有的nums
和ops
进行计算,直到没有操作或者遇到左括号,计算结果放到nums
代码实现(搬运)
public class Solution {
// 使用 map 维护一个运算符优先级(其中加减法优先级相同,乘法有着更高的优先级)
Map<Character, Integer> map = new HashMap<Character, Integer>(){{
put('-', 1);
put('+', 1);
put('*', 2);
}};
public int solve(String s) {
// 将所有的空格去掉
s = s.replaceAll(" ", "");
char[] cs = s.toCharArray();
int n = s.length();
// 存放所有的数字
Deque<Integer> nums = new ArrayDeque<>();
// 为了防止第一个数为负数,先往 nums 加个 0
nums.addLast(0);
// 存放所有「非数字以外」的操作
Deque<Character> ops = new ArrayDeque<>();
for (int i = 0; i < n; i++) {
char c = cs[i];
if (c == '(') {
ops.addLast(c);
} else if (c == ')') {
// 计算到最近一个左括号为止
while (!ops.isEmpty()) {
if (ops.peekLast() != '(') {
calc(nums, ops);
} else {
ops.pollLast();
break;
}
}
} else {
if (isNumber(c)) {
int u = 0;
int j = i;
// 将从 i 位置开始后面的连续数字整体取出,加入 nums
while (j < n && isNumber(cs[j])) u = u * 10 + (cs[j++] - '0');
nums.addLast(u);
i = j - 1;
} else {
if (i > 0 && (cs[i - 1] == '(' || cs[i - 1] == '+' || cs[i - 1] == '-')) {
nums.addLast(0);
}
// 有一个新操作要入栈时,先把栈内可以算的都算了
// 只有满足「栈内运算符」比「当前运算符」优先级高/同等,才进行运算
while (!ops.isEmpty() && ops.peekLast() != '(') {
char prev = ops.peekLast();
if (map.get(prev) >= map.get(c)) {
calc(nums, ops);
} else {
break;
}
}
ops.addLast(c);
}
}
}
// 将剩余的计算完
while (!ops.isEmpty() && ops.peekLast() != '(') calc(nums, ops);
return nums.peekLast();
}
// 计算逻辑:从 nums 中取出两个操作数,从 ops 中取出运算符,然后根据运算符进行计算即可
void calc(Deque<Integer> nums, Deque<Character> ops) {
if (nums.isEmpty() || nums.size() < 2) return;
if (ops.isEmpty()) return;
int b = nums.pollLast(), a = nums.pollLast();
char op = ops.pollLast();
int ans = 0;
if (op == '+') ans = a + b;
else if (op == '-') ans = a - b;
else if (op == '*') ans = a * b;
nums.addLast(ans);
}
boolean isNumber(char c) {
return Character.isDigit(c);
}
}
52.数组中只出现一次的数字
解题思路
利用 HashMap 记录数字出现的次数,利用 res 记录结果
代码实现
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param array int整型一维数组
* @return int整型一维数组
*/
HashMap<Integer, Integer> map = new HashMap<>();
ArrayList<Integer> res = new ArrayList<>(2);
public int[] FindNumsAppearOnce(int[] array) {
// write code here
for (int i = 0; i < array.length; i++) {
if (!map.containsKey(array[i])) {
map.put(array[i], 1);
} else {
map.put(array[i], map.get(array[i]) + 1);
}
}
for (int i = 0; i < array.length; i++) {
if (map.get(array[i]) == 1) {
res.add(array[i]);
}
}
if (res.get(0) < res.get(1)) {
return new int[]{res.get(0), res.get(1)};
} else {
return new int[]{res.get(1), res.get(0)};
}
}
}
53.缺失的第一个正整数
解题思路
依然是用 HashMap 记录数字是否出现,然后再遍历一次得出结果即可
代码实现
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @return int整型
*/
HashMap<Integer, Integer> map = new HashMap<>();
public int minNumberDisappeared(int[] nums) {
// write code here
int n = nums.length;
for (int i = 0; i < n; i++) {
map.put(nums[i], 1);
}
int res = 1;
while (map.containsKey(res)) {
res++;
}
return res;
}
}
54.三数之和
解题思路
- 排除边界特殊情况。
- 既然三元组内部要求非降序排列,那我们先得把这个无序的数组搞有序了,使用sort函数优先对其排序。
- 得到有序数组后,遍历该数组,对于每个遍历到的元素假设它是三元组中最小的一个,那么另外两个一定在后面。
- 需要三个数相加为0,则另外两个数相加应该为上述第一个数的相反数,我们可以利用双指针在剩余的子数组中找有没有这样的数对。双指针指向剩余子数组的首尾,如果二者相加为目标值,那么可以记录,而且二者中间的数字相加可能还会有。
- 如果二者相加大于目标值,说明右指针太大了,那就将其左移缩小,相反如果二者相加小于目标值,说明左指针太小了,将其右移扩大,直到两指针相遇,剩余子数组找完了。
代码实现
public class Solution {
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
ArrayList<ArrayList<Integer> > res = new ArrayList<ArrayList<Integer>>();
int n = num.length;
//不够三元组
if(n < 3)
return res;
//排序
Arrays.sort(num);
for(int i = 0; i < n - 2; i++){
if(i != 0 && num[i] == num[i - 1])
continue;
//后续的收尾双指针
int left = i + 1;
int right = n - 1;
//设置当前数的负值为目标
int target = -num[i];
while(left < right){
//双指针指向的二值相加为目标,则可以与num[i]组成0
if(num[left] + num[right] == target){
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(num[i]);
temp.add(num[left]);
temp.add(num[right]);
res.add(temp);
while(left + 1 < right && num[left] == num[left + 1])
//去重
left++;
while(right - 1 > left && num[right] == num[right - 1])
//去重
right--;
//双指针向中间收缩
left++;
right--;
}
//双指针指向的二值相加大于目标,右指针向左
else if(num[left] + num[right] > target)
right--;
//双指针指向的二值相加小于目标,左指针向右
else
left++;
}
}
return res;
}
}
很高兴大家能看到这里,其实还有大概二十来道题没有写上去,因为一方面是考虑到这些题目的使用场景,我挑选出来的题目基本都是为了应付面试,而剩下的一些题目由于条件过于精细或者是特殊性太强,因此暂不收录,感谢大家!!!