Value Filling Over Half of an Array
Problem statement
In the array nums, one value appears in more than half of the positions. Return that value.
Try to use O(n) time and only O(1) extra space.
Function
majorityValue(nums: int[]) → intExamples
Example 1
nums = [7,1,7,7,4]return = 77 appears 3 times out of 5, more than half.
Example 2
nums = [-2,-2,9,9,-2,9,-2]return = -2-2 appears 4 times out of 7 and 9 only 3, so -2 is the answer.
Example 3
nums = [42]return = 42A single value is more than half of a one-value array.
Constraints
1 <= nums.length <= 20000-10^9 <= nums[i] <= 10^9- some value appears more than
nums.length / 2times