forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_1150.java
28 lines (26 loc) · 1016 Bytes
/
_1150.java
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
package com.fishercoder.solutions;
public class _1150 {
public static class Solution1 {
/**
* credit: https://leetcode.com/problems/check-if-a-number-is-majority-element-in-a-sorted-array/discuss/358130/Java-just-one-binary-search-O(logN))-0ms-beats-100
*/
public boolean isMajorityElement(int[] nums, int target) {
int firstIndex = findFirstOccur(nums, target);
int plusHalfIndex = firstIndex + nums.length / 2;
return plusHalfIndex < nums.length && nums[plusHalfIndex] == target;
}
private int findFirstOccur(int[] nums, int target) {
int left = 0;
int right = nums.length;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] >= target) {
right = mid;
}
}
return left;
}
}
}