From eac17430175db1fa1e3ec1dafbc18b2032fe4e3b Mon Sep 17 00:00:00 2001 From: gameloader Date: Thu, 28 Mar 2024 22:28:23 +0800 Subject: [PATCH] leetcode update --- content/posts/leetcode.md | 77 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 76 insertions(+), 1 deletion(-) diff --git a/content/posts/leetcode.md b/content/posts/leetcode.md index f8b2197..18c8e1c 100644 --- a/content/posts/leetcode.md +++ b/content/posts/leetcode.md @@ -2117,7 +2117,7 @@ func abs(num int) int { ## day29 2024-03-27 -### 13. Subarray Product Less Than K +### 713. Subarray Product Less Than K Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k. @@ -2186,3 +2186,78 @@ func numSubarrayProductLessThanK(nums []int, k int) int { ``` 想到这, 忽然明白, 其实核心在于只需要考虑以某个位置为结尾的向前连续符合要求的数组长度作为该位置处应该增加的计数数目即可. 这样就把整个问题拆分成了独立不关联的小问题. 将每个位置应该增加的计数数目累积, 就是最终的结果. + +## day30 2024-03-28 + +### 2958. Length of Longest Subarray With at Most K Frequency + +You are given an integer array nums and an integer k. + +The frequency of an element x is the number of times it occurs in an array. + +An array is called good if the frequency of each element in this array is less than or equal to k. + +Return the length of the longest good subarray of nums. + +A subarray is a contiguous non-empty sequence of elements within an array. +![0328cwzoUxeYLcAx](https://testingcf.jsdelivr.net/gh/game-loader/picbase@master/uPic/0328cwzoUxeYLcAx.png) + +### 题解 + +拿到本题, 直接思路就是使用滑动窗口, 使用一个哈希表来存储每个数字对应的个数, 在滑动的过程中, 扩大窗口时增加窗口新增数字的计数并不断更新最大长度, 直到当前数字的计数达到上限k开始缩小窗口, 缩小至当前数字计数小于k(缩小过程中的数都在哈希表中对应减掉频率)即可继续扩大窗口. 如此直到遍历完整个数组. 其实从解题思路上与昨天的题内核是十分相似的. + +### 代码 + +```go +func maxSubarrayLength(nums []int, k int) int { + count := map[int]int{} + end := 0 + maxlength := 0 + for front:=0;front < len(nums);front++{ + _,exist := count[nums[front]] + if !exist{ + count[nums[front]] = 1 + }else{ + count[nums[front]]++ + } + + if count[nums[front]] <= k{ + maxlength = max(maxlength,front-end+1) + }else{ + for nums[end] != nums[front]{ + count[nums[end]]-- + end++ + } + // 将达到上限的数本身减掉 + count[nums[end]]-- + end++ + } + } + return maxlength +} + +``` + +### 总结 + +查看前面10%更快的代码, 发现判断缩小窗口的结束可以用当前窗口前端达到上限的数在哈希表中对应的计数值来判断, 缩小窗口直到达到上限的数的计数值小于k即可结束, 这样整体代码更清晰, 更简洁, 如下 + +```go +func maxSubarrayLength(nums []int, k int) int { + m := make(map[int]int) + res := 0 + for l, r := 0, 0; r < len(nums); r++ { + m[nums[r]]++ + for m[nums[r]] > k { + m[nums[l]]-- + l++ + } + + if r-l+1 > res { + res = r-l+1 + } + } + + return res +} +```