A majority element appears more than half the time. The simplest approach is to count how many times the target appears in the array by scanning through all elements. If the count exceeds n/2, the target is a majority element.
true if the count is greater than half the array length, false otherwise.Where is the size of
nums.
Since the array is sorted, all occurrences of the target are contiguous. We can use binary search to find the first and last occurrence of the target. The count is simply (lastIndex - firstIndex + 1), which we compare against n/2.
lower_bound to find the index of the first element >= target.upper_bound to find the index of the first element > target.upper_bound - lower_bound).true if this count is greater than n/2.class Solution:
def lower_bound(self, nums: List[int], target: int) -> int:
"""
Returns the index of the first element equal to or greater than the target.
If there is no instance of the target in the list, it returns the length of the list.
"""
start = 0
end = len(nums) - 1
index = len(nums)
while start <= end:
mid = (start + end) // 2
if nums[mid] >= target:
end = mid - 1
index = mid
else:
start = mid + 1
return index
def upper_bound(self, nums: List[int], target: int) -> int:
"""
Returns the index of the first element greater than the target.
If there is no instance of the target in the list, it returns the length of the list.
"""
start = 0
end = len(nums) - 1
index = len(nums)
while start <= end:
mid = (start + end) // 2
if nums[mid] > target:
end = mid - 1
index = mid
else:
start = mid + 1
return index
def isMajorityElement(self, nums: List[int], target: int) -> bool:
first_index = self.lower_bound(nums, target)
next_to_last_index = self.upper_bound(nums, target)
return next_to_last_index - first_index > len(nums) // 2Where is the size of
nums.
If the target is a majority element, it must occupy more than half the array positions. This means if we find the first occurrence at index i, the element at index i + n/2 must also be the target. We only need one binary search to find the first occurrence, then check this specific position.
lower_bound to find the first occurrence of the target at index i.i + n/2 (where n is the array length).true.false.class Solution:
def lower_bound(self, nums: List[int], target: int) -> int:
"""
Returns the index of the first element that is equal to or greater than the target.
If there is no instance of the target in the list, it returns the length of the list.
"""
start = 0
end = len(nums) - 1
index = len(nums)
while start <= end:
mid = (start + end) // 2
if nums[mid] >= target:
end = mid - 1
index = mid
else:
start = mid + 1
return index
def isMajorityElement(self, nums: List[int], target: int) -> bool:
first_index = self.lower_bound(nums, target)
return first_index + len(nums) // 2 < len(nums) and nums[first_index + len(nums) // 2] == targetWhere is the size of
nums.