๐ ๋ฌธ์
You are given a 0-indexed integer array nums of size n, and a 0-indexed integer array pattern of size m consisting of integers -1, 0, and 1.
A subarray nums[i..j] of size m + 1 is said to match the pattern if the following conditions hold for each element pattern[k]:
- nums[i + k + 1] > nums[i + k] if pattern[k] == 1.
- nums[i + k + 1] == nums[i + k] if pattern[k] == 0.
- nums[i + k + 1] < nums[i + k] if pattern[k] == -1.
Return the count of subarrays in nums that match the pattern.
๐ซ ์์
Input: nums = [1,2,3,4,5,6], pattern = [1,1]
Output: 4
Explanation: The pattern [1,1] indicates that we are looking for strictly increasing subarrays of size 3. In the array nums, the subarrays [1,2,3], [2,3,4], [3,4,5], and [4,5,6] match this pattern.
Hence, there are 4 subarrays in nums that match the pattern.
๐ฑ ์ ํ
- 2 <= n == nums.length <= 106
- 1 <= nums[i] <= 109
- 1 <= m == pattern.length < n
- -1 <= pattern[i] <= 1
๐ ๋ฌธ์ ํ์ด
๋ฌธ์ ๋ฅผ ์ ๋ฆฌํด๋ณด์๋ฉด nums ์์ pattern ์ ๋ฑ์ฅ ํ์๋ฅผ ์ฐพ๋ ๋ฌธ์ ์ด๋ค.
nums ๋ pattern ์ด๋ ๋ฐ๋ก ๋งค์นญ์ด ๋๋๋ก nums[i] < nums[i+1] ์ด๋ฉด 1, nums[i] == nums[i+1] ์ด๋ฉด 0, nums[i] > nums[i+1] ์ด๋ฉด -1 ์ธ ์๋ก์ด ๋ฐฐ์ด์ ๋ง๋ ๋ค์ ์ด ๋ฐฐ์ด์์ pattern์ ๋ฑ์ฅ ํ์๋ KMP ์๊ณ ๋ฆฌ์ฆ์ ์ฌ์ฉํ์ฌ ๋น ๋ฅด๊ฒ ํด๊ฒฐํ ์ ์๋ค.
๐ป ์ฝ๋
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | class Solution: def countMatchingSubarrays(self, nums: List[int], pattern: List[int]) -> int: n = len(nums) pre = [] for i in range(n-1): if nums[i] < nums[i+1]: pre.append(1) elif nums[i] > nums[i+1]: pre.append(-1) else: pre.append(0) # kmp m = len(pattern) fail = [0]*m i = 0 for j in range(1, m): while i > 0 and pattern[i] != pattern[j]: i = fail[i-1] if pattern[i] == pattern[j]: i += 1 fail[j] = i res = 0 i = 0 for j in range(n-1): while i > 0 and pre[j] != pattern[i]: i = fail[i-1] if pattern[i] == pre[j]: i += 1 if i == len(pattern): res += 1 i = fail[i-1] return res | cs |
๐ ๋ฌธ์ ๋งํฌ
'Problem Solving > ๋ฆฌํธ์ฝ๋' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LeetCode] 2563. Count the Number of Fair Pairs (0) | 2024.11.13 |
---|---|
[LeetCode] 406. Queue Reconstruction by Height (2) | 2024.11.08 |
[LeetCode] 380. Insert Delete GetRandom O(1) (1) | 2024.01.21 |
[LeetCode] 1657. Determine if Two Strings Are Close (1) | 2024.01.14 |