zoukankan      html  css  js  c++  java
  • 【leetcode】1566. Detect Pattern of Length M Repeated K or More Times

    题目如下:

    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 = 3
    Output: true
    Explanation: 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 = 2
    Output: true
    Explanation: 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 = 3
    Output: false
    Explanation: 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 = 2
    Output: false
    Explanation: 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 = 3
    Output: false
    Explanation: 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 <= 100
    • 1 <= arr[i] <= 100
    • 1 <= m <= 100
    • 2 <= k <= 100

    解题思路:本题是要判断arr中是否存在这样的子数组,其长度是m*k,并且子数组可以分成长度为m的k个孙数组,满足k个数组的元素和顺序完全一致。假设arr[i]是这样子数组的第一个元素,只要判断 arr[i:i+m] * k == arr[i:i+m*k] 即可。

    代码如下:

    class Solution(object):
        def containsPattern(self, arr, m, k):
            """
            :type arr: List[int]
            :type m: int
            :type k: int
            :rtype: bool
            """
            for i in range(len(arr)-m):
                if i+m*k <= len(arr) and arr[i:i+m] * k == arr[i:i+m*k]:
                    return True
            return False
  • 相关阅读:
    BPC (9) SAP BI & BPC 安装 : 一个外行眼里的千奇百怪 (1)
    ESB (2) POCSofewareAG
    BPC (7) BPC Netweaver 7 和 microsoft 7 版本的差异
    ESB (3) POCOralce ESB
    厘清了xorg里的一些概念
    Top命令和Kill命令
    ubuntu中文英文环境切换
    /etc/passwd 文件内容详细解释
    [分享] Linux下用Anjuta写个Hello World 的C++程序竟如此简单!
    /proc目录
  • 原文地址:https://www.cnblogs.com/seyjs/p/13999561.html
Copyright © 2011-2022 走看看