LeetCode 题解工作台
重复至少 K 次且长度为 M 的模式
给你一个正整数数组 arr ,请你找出一个长度为 m 且在数组中至少重复 k 次的模式。 模式 是由一个或多个值组成的子数组(连续的子序列), 连续 重复多次但 不重叠 。 模式由其长度和重复次数定义。 如果数组中存在至少重复 k 次且长度为 m 的模式,则返回 true ,否则返回 false 。…
2
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·结合·enumeration
答案摘要
首先,如果数组的长度小于 $m \times k$,那么肯定不存在长度为 且至少重复 次的模式,直接返回 。 接下来,我们定义一个变量 来记录当前连续重复的次数,如果数组存在连续的 $(k - 1) \times m$ 个元素 ,使得 $a_i = a_{i - m}$,那么我们就找到了一个长度为 且至少重复 次的模式,返回 。否则,我们将 置为 ,继续遍历数组。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·结合·enumeration 题型思路
题目描述
给你一个正整数数组 arr,请你找出一个长度为 m 且在数组中至少重复 k 次的模式。
模式 是由一个或多个值组成的子数组(连续的子序列),连续 重复多次但 不重叠 。 模式由其长度和重复次数定义。
如果数组中存在至少重复 k 次且长度为 m 的模式,则返回 true ,否则返回 false 。
示例 1:
输入:arr = [1,2,4,4,4,4], m = 1, k = 3 输出:true 解释:模式 (4) 的长度为 1 ,且连续重复 4 次。注意,模式可以重复 k 次或更多次,但不能少于 k 次。
示例 2:
输入:arr = [1,2,1,2,1,1,1,3], m = 2, k = 2 输出:true 解释:模式 (1,2) 长度为 2 ,且连续重复 2 次。另一个符合题意的模式是 (2,1) ,同样重复 2 次。
示例 3:
输入:arr = [1,2,1,2,1,3], m = 2, k = 3 输出:false 解释:模式 (1,2) 长度为 2 ,但是只连续重复 2 次。不存在长度为 2 且至少重复 3 次的模式。
示例 4:
输入:arr = [1,2,3,1,2], m = 2, k = 2 输出:false 解释:模式 (1,2) 出现 2 次但并不连续,所以不能算作连续重复 2 次。
示例 5:
输入:arr = [2,2,2,2], m = 2, k = 3 输出:false 解释:长度为 2 的模式只有 (2,2) ,但是只连续重复 2 次。注意,不能计算重叠的重复次数。
提示:
2 <= arr.length <= 1001 <= arr[i] <= 1001 <= m <= 1002 <= k <= 100
解题思路
方法一:一次遍历
首先,如果数组的长度小于 ,那么肯定不存在长度为 且至少重复 次的模式,直接返回 。
接下来,我们定义一个变量 来记录当前连续重复的次数,如果数组存在连续的 个元素 ,使得 ,那么我们就找到了一个长度为 且至少重复 次的模式,返回 。否则,我们将 置为 ,继续遍历数组。
最后,如果遍历完数组都没有找到符合条件的模式,返回 。
时间复杂度 ,其中 是数组的长度。空间复杂度 。
class Solution:
def containsPattern(self, arr: List[int], m: int, k: int) -> bool:
if len(arr) < m * k:
return False
cnt, target = 0, (k - 1) * m
for i in range(m, len(arr)):
if arr[i] == arr[i - m]:
cnt += 1
if cnt == target:
return True
else:
cnt = 0
return False
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n*m) due to iterating over each starting index and comparing up to m elements for each repetition check. Space complexity is O(1) extra since comparisons can be done in place without additional storage. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Looking for awareness of pattern repetition and consecutive subarray detection.
- question_mark
Checking if you handle overlaps and edge cases correctly when counting repetitions.
- question_mark
Evaluating whether the candidate optimizes comparisons instead of naïve slice copying.
常见陷阱
外企场景- error
Not verifying consecutive repetitions correctly, leading to false positives.
- error
Incorrectly handling overlaps or resetting the repetition count at wrong positions.
- error
Assuming any repeated sequence counts without enforcing exact length m and minimum k repetitions.
进阶变体
外企场景- arrow_right_alt
Check for repeated patterns allowing gaps between repetitions rather than strictly consecutive.
- arrow_right_alt
Count the total number of different patterns of length m repeated at least k times.
- arrow_right_alt
Detect the longest pattern that is repeated consecutively at least k times and return its length.