diff --git a/.eslintrc.json b/.eslintrc.json index 03e9b7c..940d073 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -22,6 +22,7 @@ "no-constant-condition": "off", // 允许while(true) "default-case": "off", // 允许switch不写default "no-fallthrough": "off", // 允许case穿透 + "prefer-destructuring": ["error", {"object": false, "array": false}], "import/extensions": [ "error", "ignorePackages", // 忽略 node_modules 内的包 diff --git a/binary-search/35搜索插入位置.js b/binary-search/35搜索插入位置.js new file mode 100644 index 0000000..96d7ec6 --- /dev/null +++ b/binary-search/35搜索插入位置.js @@ -0,0 +1,36 @@ +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +const searchInsert = function (nums, target) { + +}; + +/* +直接使用二分查找,二分查找没什么好说的,但是这个题目中target不一定存在nums中,所以需要设置一个pos遍历来保存,target应该插入的位置, +我们只需在target < nums[mid]的时候设置一次就行,初始化pos的index=nums.length +*/ + +function f2(nums, target) { + let pos = nums.length; + let left = 0; + let right = nums.length - 1; + + // 二分查找知道left>right结束查找 + while (left <= right) { + const mid = Math.floor((left + right) / 2); + // 如果target temperatures[stack[stack.length - 1]]) { + const cur = stack.pop(); + res[cur] = i - cur; + } + // 将当前元素下标压入栈中 + stack.push(i); + } + } + + // 如果栈中还有元素,将其在result中的对应位置设置从0,表示后面没有元素大于当前位置的元素 + for (const i of stack) { + res[i] = 0; + } + + return res; +} + +/* +chatgpt 优化之后的写法,思路没有变,去除了if判断,逻辑如下: +遍历整个温度,如果单调栈有元素,并且当前元素大于栈顶元素,就一直处理,直到栈中没有元素,或者当前元素小于等于栈顶元素 +然后将当前元素压入栈中 +*/ + +/** + * 计算每一天需要等待多少天才会有更高温度。 + * 如果后面没有更高的温度,则返回 0。 + * + * @param {number[]} temperatures - 每天的温度数组 + * @returns {number[]} - 返回一个数组,表示每一天距离下一次更高温度的天数 + */ +function f2(temperatures) { + // 初始化结果数组,默认所有值为 0(表示找不到更高温度) + const res = new Array(temperatures.length).fill(0); + + // 用来存储下标的单调递减栈(栈顶到栈底的温度依次递减) + const stack = []; + + // 遍历温度数组 + for (let i = 0; i < temperatures.length; i++) { + const currentTemp = temperatures[i]; + + /** + * 当前温度比栈顶下标对应的温度大,说明当前是“更高温度”的一天, + * 所以可以开始出栈并记录距离。 + * + * 注意:每个元素最多被 push 和 pop 各一次,所以总体时间复杂度是 O(n) + */ + while ( + stack.length > 0 + && currentTemp > temperatures[stack[stack.length - 1]] + ) { + // 栈顶元素下标 + const prevIndex = stack.pop(); + + // 当前天(i)就是之前那天(prevIndex)等待的更高温度的那一天 + res[prevIndex] = i - prevIndex; + } + + // 无论如何都要把当前下标压栈,作为之后判断的基准 + stack.push(i); + } + + // 栈中剩下的下标所对应的位置已经默认填 0,不需要再处理 + return res; +}