不积跬步,无以至千里;不积小流,无以成江海
时间:2020-5-29 讨论: 代码地址:https://leetcode.cn/contest/weekly-contest-295
A: 重排字符形成目标字符串
思路:木桶原理,统计
关键点:
function rearrangeCharacters(s: string, target: string): number {let cnt1 = new Array(128).fill(0),cnt2 = new Array(128).fill(0);for (let i of target) {cnt1[i.charCodeAt(0)]++;}for (let i of s) {cnt2[i.charCodeAt(0)]++;}const max = Number.MAX_SAFE_INTEGER;let ans = max;for (let i = 0; i < 128; i++) {if (cnt1[i] === 0) continue;ans = Math.min(ans, Math.floor(cnt2[i] / cnt1[i]));}return ans === max ? 0 : ans;};
总结:
B: 价格减免
思路:
- 转为数组
- 匹配合法数据
- 针对目标数据进行操作
- 保留两位小数
- 还原为字符串
1. 判断非负实数正则
new RegExp(/^(\$)(([1-9]\d.?\d)|(0.\d*))$/g);
2. String.prototype.replace
str.replace(regexp|substr, newSubStr|function)
function discountPrices(sentence: string, discount: number): string {const sell = (100 - discount) / 100;let reg = new RegExp(/^(\$)(([1-9]\d*\.?\d*)|(0\.\d*))$/g);let arr = sentence.split(' ').map(d => {if (!reg.test(d)) return d;return d.replace(reg, (s, $1, $2) => {return `$${(sell * $2).toFixed(2)}`;});});return arr.join(' ');};
总结:
C: 使数组按非递减顺序排列
思路:
关键点:单调栈
function totalSteps(nums: number[]): number {let ans = 0;let stack = [];for (let num of nums) {let max = 0;while (stack.length && stack[0][0] <= num) {max = Math.max(stack[0][1], max);stack.shift();}if (stack.length) max++;ans = Math.max(max, ans);stack.unshift([num, max]);}return ans;};
总结:
case: [10,1,2,3,4,5,6,1,2,3]
练习: 单调栈
D: 到达角落需要移除障碍物的最小数目
最短路径问题
思路:
关键点:0-1BFS
function minimumObstacles(grid: number[][]): number {const m = grid.length, n = grid[0].length;const dirs = [[0, 1], [0, -1], [1, 0], [-1, 0]];let ans = Array.from({ length: m }, v => new Array(n).fill(Infinity));ans[0][0] = 0;let deque = [[0, 0]];while (deque.length) {let [x, y] = deque.shift();for (let [dx, dy] of dirs) {let [i, j] = [x + dx, y + dy];if (i < 0 || i > m - 1 || j < 0 || j > n - 1) continue;const cost = grid[i][j];if (ans[x][y] + cost >= ans[i][j]) continue;ans[i][j] = ans[x][y] + cost;deque.push([i, j]);// if (cost) deque.push([i, j]);// else deque.unshift([i, j]);}}return ans[m - 1][n - 1];};
总结:使用双向队列超时
1368. 使网格图至少有一条有效路径的最小代价
复盘

A: 基础题
B: 依赖谷歌正则表达式 -> 巩固正则
C: 缺失单调栈积累
D: 缺失最优路径问题积累
反思:
js语言在缺失内置复杂数据类型、较复杂类型下超时
考虑提升CD类型通过率, 切换其他类型语言并加大练习
