Suppose we have an array called, nums and that is sorted in non-decreasing order, and a number target. We have to find if the target is a majority element. In an array a majority element is an element that appears more than N/2 times in an array of length N. So if the array is like − [2,4,5,5,5,5,5,6,6] and target is 5, then output is true.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class Solution(object): def upper(self,n,target): low = 0 high = len(n)-1 while low<high: mid = low + (high - low + 1)//2 if n[mid] == target: low = mid else: high = mid-1 return low if n[low] == target else -1 def lower(self,n,target): low = 0 high = len(n)-1 while low < high: mid = low + (high - low)//2 if n[mid]== target: high = mid else : low = mid +1 return high if n[high] == target else -1 def isMajorityElement(self, nums, target): u = self.upper(nums,target) l = self.lower(nums,target) return u-l+1 >len(nums)/2 if u != -1 else False ob1 = Solution() print(ob1.isMajorityElement([2,4,5,5,5,5,5,6,6], 5))