- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_1150.java
28 lines (26 loc) · 1.01 KB
/
_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
packagecom.fishercoder.solutions.secondthousand;
publicclass_1150 {
publicstaticclassSolution1 {
/*
* 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
*/
publicbooleanisMajorityElement(int[] nums, inttarget) {
intfirstIndex = findFirstOccur(nums, target);
intplusHalfIndex = firstIndex + nums.length / 2;
returnplusHalfIndex < nums.length && nums[plusHalfIndex] == target;
}
privateintfindFirstOccur(int[] nums, inttarget) {
intleft = 0;
intright = nums.length;
while (left < right) {
intmid = left + (right - left) / 2;
if (nums[mid] < target) {
left = mid + 1;
} elseif (nums[mid] >= target) {
right = mid;
}
}
returnleft;
}
}
}