[LeetCode] Check If a Number Is Majority Element in a Sorted Array

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

Given an integer array nums sorted in non-decreasing order and an integer target, return true if target is a majority element, or false otherwise.

A majority element in an array nums is an element that appears more than nums.length / 2 times in the array.

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
bool isMajorityElement(vector<int>& nums, int target) {
auto st = lower_bound(nums.begin(), nums.end(), target);
if(st == end(nums) or *st != target) return false;
auto ed = upper_bound(nums.begin(), nums.end(), target);
auto cnt = ed - st;
return nums.size() < cnt * 2;

}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/02/PS/LeetCode/check-if-a-number-is-majority-element-in-a-sorted-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.