leetcode-1566-easy

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.
Constraints:

2 <= arr.length <= 100
1 <= arr[i] <= 100
1 <= m <= 100
2 <= k <= 100

思路一:这题和 1668 非常像。从数组 [0, length-1],我们需要遍历每一位,在数组匹配中,有个难点是需要对比的位置 arr[i] == arr[((i - begin) % m)+begin], 可以分成两部分 (i-begin) % m + begin 来分析,第一部分是为了定位开始重复串 m 的第几个位置,第二部分为了正确匹配 i 的位置

public boolean containsPattern(int[] arr, int m, int k) {
    for (int i = 0; i < arr.length; i++) {
        if (containsPattern(arr, m, k, i)) return true;
    }

    return false;
}

public boolean containsPattern(int[] arr, int m, int k, int begin) {
    int count = 0;
    for (int i = begin; i < arr.length; i++) {
        if (arr[i] == arr[((i - begin) % m)+begin]) {
            count++;
        } else {
            break;
        }

        if (count / m >= k) return true;
    }

    return false;
}
posted @ 2022-11-03 18:34  iyiluo  阅读(18)  评论(0)    收藏  举报