You are given an integer array nums and an integer target.
Return the number of subarrays of nums in which target is the majority element.
The majority element of a subarray is the element that appears strictly more than half of the times in that subarray.
[1, 2, 2, 3], 타겟: 2
class Solution:
def countMajoritySubarrays(self, nums: List[int], target: int) -> int:
N = len(nums)
count = [0] * (N + 1)
for i in range(1, N + 1):
if nums[i - 1] == target:
count[i] += 1
else:
count[i] -= 1
count[i] += count[i - 1]
self.ans = 0
def checker(start: int, mid: int, end: int):
j = mid + 1
for i in range(start, mid + 1):
while j <= end and count[j] <= count[i]:
j += 1
self.ans += end - j + 1
temp = []
l = start
r = mid + 1
while l <= mid and r <= end:
if count[l] <= count[r]:
temp.append(count[l])
l += 1
else:
temp.append(count[r])
r += 1
while l <= mid:
temp.append(count[l])
l += 1
while r <= end:
temp.append(count[r])
r += 1
for i, v in enumerate(temp):
count[start + i] = v
def counter(start: int, end: int):
if start >= end:
return
mid = (start + end) // 2
counter(start, mid)
counter(mid + 1, end)
checker(start, mid, end)
counter(0, N)
return self.ans
class Solution:
def countMajoritySubarrays(self, nums: List[int], target: int) -> int:
N = len(nums)
freq = defaultdict(int)
freq[0] = 1
value = 0
ans = 0
old = 0
for i in range(1, N + 1):
if nums[i - 1] == target:
old += 1
value += freq[old - 1]
else:
old -= 1
value -= freq[old]
ans += value
freq[old] += 1
return ans