MrainW's Home

All things come to those who wait!

0%

LeetCode 169. Majority Element

Question

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.

https://leetcode.com/problems/majority-element/

  • Solution1
1
2
3
4
5
6
7
8
9
10
class Solution {
public int majorityElement(int[] nums) {
int count = 0, candidate = 0;
for (int num : nums){
if (count == 0) candidate = num;
count += (num == candidate) ? 1 : -1;
}
return candidate;
}
}

Complexity:

Time complexity: O( n)

Space complexity: O(1)

Welcome to my other publishing channels