Majority Element
Given an array nums of size n, return the majority element, the value that appears more than n/2 times. You may assume that a majority element always exists.
Open official problem prompt ↗Identify the value occupying more than half the array using constant extra memory.
Like an election where every non-majority voter can be paired to knock out one majority voter; because the majority has more than half the votes, at least one of theirs is always left standing.
- Input
- nums = [2, 2, 1, 1, 1, 2, 2]
- Output
- 2
- Why
- 2 appears 4 times out of 7, which is more than 7/2 = 3.5.
n == nums.length1 <= n <= 5 * 10^4-10^9 <= nums[i] <= 10^9A majority element is guaranteed to exist