0%

Check If a Number Is Majority Element in a Sorted Array

Question

Given an array nums sorted in non-decreasing order, and a number target, return True if and only if target is a majority element.

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

Example:
Input: nums = [2,4,5,5,5,5,5,6,6], target = 5
Output: true

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public boolean isMajorityElement(int[] nums, int target) {
int len = nums.length;
if (len == 0) {
return false;
}
if (len == 1) {
return nums[0] == target;
}

int index = -1;
for (int i = 0; i < len; i++) {
if (nums[i] == target) {
if (index == -1) {
index = i;
}else if (i == len-1 || nums[i+1] != target) {
if (i-index+1 > len/2) {
return true;
}
}

}
}
return false;
}