Skip to content

1150. Check If a Number Is Majority Element in a Sorted Array 👍

  • Time: $O(\log n)$
  • Space: $O(1)$
1
2
3
4
5
6
7
8
class Solution {
 public:
  bool isMajorityElement(vector<int>& nums, int target) {
    const int n = nums.size();
    const int i = ranges::lower_bound(nums, target) - nums.begin();
    return i + n / 2 < n && nums[i + n / 2] == target;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public boolean isMajorityElement(int[] nums, int target) {
    final int n = nums.length;
    final int i = firstGreaterEqual(nums, target);
    return i + n / 2 < n && nums[i + n / 2] == target;
  }

  private int firstGreaterEqual(int[] A, int target) {
    int l = 0;
    int r = A.length;
    while (l < r) {
      final int m = (l + r) / 2;
      if (A[m] >= target)
        r = m;
      else
        l = m + 1;
    }
    return l;
  }
}
1
2
3
4
5
class Solution:
  def isMajorityElement(self, nums: list[int], target: int) -> bool:
    n = len(nums)
    i = bisect.bisect_left(nums, target)
    return i + n // 2 < n and nums[i + n // 2] == target