Check If a Number Is Majority Element in a Sorted Array

easy binary search array majority element

Problem

Given an integer array nums sorted in non-decreasing order and a number target, return true if target is a majority element, and false otherwise. A majority element is an element that appears more than nums.length / 2 times in the array.

Inputnums = [2, 4, 5, 5, 5, 5, 5, 6, 6], target = 5
Outputtrue
5 appears 5 times and 5 > 9 / 2 = 4.5, so it is a majority element.

def is_majority_element(nums, target):
    n = len(nums)
    lo = bisect_left(nums, target)
    if lo == n or nums[lo] != target:
        return False
    return lo + n // 2 < n and nums[lo + n // 2] == target
function isMajorityElement(nums, target) {
  const n = nums.length;
  const lo = lowerBound(nums, target);
  if (lo === n || nums[lo] !== target) return false;
  const mid = lo + ((n / 2) | 0);
  return mid < n && nums[mid] === target;
}
class Solution {
    public boolean isMajorityElement(int[] nums, int target) {
        int n = nums.length;
        int lo = lowerBound(nums, target);
        if (lo == n || nums[lo] != target) return false;
        int mid = lo + n / 2;
        return mid < n && nums[mid] == target;
    }
}
bool isMajorityElement(vector<int>& nums, int target) {
    int n = nums.size();
    int lo = lower_bound(nums.begin(), nums.end(), target) - nums.begin();
    if (lo == n || nums[lo] != target) return false;
    int mid = lo + n / 2;
    return mid < n && nums[mid] == target;
}
Time: O(log n) Space: O(1)