g0101_0200.s0169_majority_element.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0101_0200.s0169_majority_element;
// #Easy #Top_100_Liked_Questions #Top_Interview_Questions #Array #Hash_Table #Sorting #Counting
// #Divide_and_Conquer #Data_Structure_II_Day_1_Array #Udemy_Famous_Algorithm
// #Big_O_Time_O(n)_Space_O(1) #2022_06_25_Time_1_ms_(100.00%)_Space_45.5_MB_(97.51%)
/**
* 169 - Majority Element\.
*
* Easy
*
* Given an array `nums` of size `n`, return _the majority element_.
*
* The majority element is the element that appears more than `⌊n / 2⌋` times. You may assume that the majority element always exists in the array.
*
* **Example 1:**
*
* **Input:** nums = [3,2,3]
*
* **Output:** 3
*
* **Example 2:**
*
* **Input:** nums = [2,2,1,1,1,2,2]
*
* **Output:** 2
*
* **Constraints:**
*
* * `n == nums.length`
* * 1 <= n <= 5 * 104
* * -231 <= nums[i] <= 231 - 1
*
* **Follow-up:** Could you solve the problem in linear time and in `O(1)` space?
**/
public class Solution {
public int majorityElement(int[] arr) {
int count = 1;
int majority = arr[0];
// For Potential Majority Element
for (int i = 1; i < arr.length; i++) {
if (arr[i] == majority) {
count++;
} else {
if (count > 1) {
count--;
} else {
majority = arr[i];
}
}
}
// For Confirmation
count = 0;
for (int j : arr) {
if (j == majority) {
count++;
}
}
if (count >= (arr.length / 2) + 1) {
return majority;
} else {
return -1;
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy