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

这题一开始想复杂了,做了个不连续的子串判断。后面改了一下就行了,不过貌似时间复杂度不是最优。


class DetectPatternOfLengthMRepeatedKOrMoreTimes : public Solution {
public:
    void Exec() {

    }
    bool containsPattern(vector<int>& arr, int m, int k) {
        for (int off = 0; off < arr.size(); off ++) {
            if (arr.size() - 1 - off + 1 < k * m) {
                break;
            }
            for (int i = 0; i < k; i++) {
                if (0 != memcmp(&arr[off], &arr[off + i * m], sizeof(int) * m)) {
                    break;
                }
                if (i == k - 1) {
                    return true;
                }
            }
        }
        return false;
    }
    bool containsPatternNotConsecutive(vector<int>& arr, int m, int k) {
        for (int off = 0; off < arr.size(); off ++) {
            int count = 1;
            for (int i = off + m; i < arr.size() - m * (k - count) + 1; ) {
                if (0 == memcmp(&arr[off], &arr[i], sizeof(int) * m)) {
                    count++;
                    i += m;
                } else {
                    i++;
                }
                if (count == k) {
                    return true;
                }
            }
        }
        return false;
    }
};
共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day