Skip to content

Commit 45b1704

Browse files
refactor 1150
1 parent c5026c8 commit 45b1704

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

src/main/java/com/fishercoder/solutions/_1150.java

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,25 @@
2727
**/
2828
public class _1150 {
2929
public static class Solution1 {
30+
/**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*/
3031
public boolean isMajorityElement(int[] nums, int target) {
31-
return nums[(nums.length - 1) / 2] == target;
32+
int firstIndex = findFirstOccur(nums, target);
33+
int plusHalfIndex = firstIndex + nums.length / 2;
34+
return plusHalfIndex < nums.length && nums[plusHalfIndex] == target;
35+
}
36+
37+
private int findFirstOccur(int[] nums, int target) {
38+
int left = 0;
39+
int right = nums.length;
40+
while (left < right) {
41+
int mid = left + (right - left) / 2;
42+
if (nums[mid] < target) {
43+
left = mid + 1;
44+
} else if (nums[mid] >= target) {
45+
right = mid;
46+
}
47+
}
48+
return left;
3249
}
3350
}
3451
}

src/test/java/com/fishercoder/_1150Test.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,10 @@ public void test2() {
2727
assertEquals(false, solution1.isMajorityElement(nums, 101));
2828
}
2929

30+
@Test
31+
public void test3() {
32+
nums = new int[]{1, 1, 1, 2, 3, 3, 3};
33+
assertEquals(false, solution1.isMajorityElement(nums, 2));
34+
}
35+
3036
}

0 commit comments

Comments
 (0)