-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy path1150-check-if-a-number-is-majority-element-in-a-sorted-array.js
More file actions
56 lines (51 loc) · 1.4 KB
/
1150-check-if-a-number-is-majority-element-in-a-sorted-array.js
File metadata and controls
56 lines (51 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
* 1150. Check If a Number Is Majority Element in a Sorted Array
* https://leetcode.com/problems/check-if-a-number-is-majority-element-in-a-sorted-array/
* Difficulty: Easy
*
* 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.
*/
/**
* @param {number[]} nums
* @param {number} target
* @return {boolean}
*/
var isMajorityElement = function(nums, target) {
const firstIndex = findFirstIndex(target);
if (firstIndex >= nums.length || nums[firstIndex] !== target) {
return false;
}
const lastIndex = findLastIndex(target);
const frequency = lastIndex - firstIndex + 1;
return frequency > nums.length / 2;
function findFirstIndex(target) {
let left = 0;
let right = nums.length;
while (left < right) {
const mid = Math.floor((left + right) / 2);
if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
function findLastIndex(target) {
let left = 0;
let right = nums.length;
while (left < right) {
const mid = Math.floor((left + right) / 2);
if (nums[mid] <= target) {
left = mid + 1;
} else {
right = mid;
}
}
return left - 1;
}
};