轻量级前端框架助力开发者提升项目效率与性能
702
2022-09-05
[leetcode] 1566. Detect Pattern of Length M Repeated K or More Times
Description
Given an array of positive integers arr, find a pattern of length m that is repeated k or more times.
A pattern is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times consecutively without overlapping. A pattern is defined by its length and the number of repetitions.
Return true if there exists a pattern of length m that is repeated k or more times, otherwise return false.
Example 1:
Input: arr = [1,2,4,4,4,4], m = 1, k = 3Output: trueExplanation: The pattern (4) of length 1 is repeated 4 consecutive times. Notice that pattern can be repeated k or more times but not less.
Example 2:
Input: arr = [1,2,1,2,1,1,1,3], m = 2, k = 2Output: trueExplanation: The pattern (1,2) of length 2 is repeated 2 consecutive times. Another valid pattern (2,1) is also repeated 2 times.
Example 3:
Input: arr = [1,2,1,2,1,3], m = 2, k = 3Output: falseExplanation: The pattern (1,2) is of length 2 but is repeated only 2 times. There is no pattern of length 2 that is repeated 3 or more times.
Example 4:
Input: arr = [1,2,3,1,2], m = 2, k = 2Output: falseExplanation: Notice that the pattern (1,2) exists twice but not consecutively, so it doesn't count.
Example 5:
Input: arr = [2,2,2,2], m = 2, k = 3Output: falseExplanation: The only pattern of length 2 is (2,2) however it's repeated only twice. Notice that we do not count overlapping repetitions.
Constraints:
2 <= arr.length <= 1001 <= arr[i] <= 1001 <= m <= 1002 <= k <= 100
分析
题目的意思是:给你一个数组,找出重复超过K次的子数组,这道题目虽然是easy类型,我没啥思路,关键在于暴力破解写三个循环有点麻烦,参考了一下别人的实现,首先遍历数组,然后判断把一个子数组拓展K次是否等于相对应位置的值,这样就很容易判别出来了,python这种数组进行比较的做法还是挺巧妙的。
class Solution: def containsPattern(self, arr: List[int], m: int, k: int) -> bool: n=len(arr) if(m*k>n): return False for i in range(n-m): if(arr[i:i+m]*k==arr[i:i+m*k]): return True return False
参考文献
[LeetCode] [Python 3] Short solution faster than 92%
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~