LeetCode 1150: Check If a Number Is Majority Element in a Sorted Array Solution
Master LeetCode problem 1150 (Check If a Number Is Majority Element in a Sorted Array), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1150. Check If a Number Is Majority Element in a Sorted Array
Problem Explanation
Explanation
Given a sorted array of integers, we need to check if a specific number appears more than n/2 times, where n is the length of the array. We can use binary search to find the first and last occurrences of the number in the array. If the count of occurrences is greater than n/2, then the number is a majority element.
Algorithm:
- Find the first occurrence of the number using binary search.
- Find the last occurrence of the number using binary search.
- Calculate the count of occurrences.
- Check if the count is greater than n/2.
Time Complexity: O(log n) - Binary search Space Complexity: O(1)
Solution Code
class Solution {
public boolean isMajorityElement(int[] nums, int target) {
int first = findFirstOccurrence(nums, target);
int last = findLastOccurrence(nums, target);
int count = last - first + 1;
int n = nums.length;
return count > n / 2;
}
private int findFirstOccurrence(int[] nums, int target) {
int low = 0, high = nums.length - 1;
while (low < high) {
int mid = low + (high - low) / 2;
if (nums[mid] < target) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
}
private int findLastOccurrence(int[] nums, int target) {
int low = 0, high = nums.length - 1;
while (low < high) {
int mid = low + (high - low + 1) / 2;
if (nums[mid] > target) {
high = mid - 1;
} else {
low = mid;
}
}
return low;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1150 (Check If a Number Is Majority Element in a Sorted Array)?
This page provides optimized solutions for LeetCode problem 1150 (Check If a Number Is Majority Element in a Sorted Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1150 (Check If a Number Is Majority Element in a Sorted Array)?
The time complexity for LeetCode 1150 (Check If a Number Is Majority Element in a Sorted Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1150 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1150 in Java, C++, or Python.