Majority Element
Problem statement
Given a non-empty integer array nums, return its majority element.
The majority element appears more than floor(nums.length / 2) times. You may assume that such an element always exists.
Your solution must run in O(n) time and use O(1) extra space.
Function
majorityElement(nums: int[]) → intExamples
Example 1
nums = [3,2,3]return = 3The value 3 appears twice in an array of length 3.
Example 2
nums = [2,2,1,1,1,2,2]return = 2The value 2 appears four times, which is more than half of 7.
Example 3
nums = [-1,-1,-1,2,3]return = -1The majority value may be negative.
Constraints
1 <= nums.length <= 100000- Every value fits in a signed 32-bit integer.
- Exactly one value appears more than
floor(nums.length / 2)times.