While working on this particular problem on Leetcode, I came across a solution that left me puzzled.
The solution suggested to "sort the array and the middle element will be the majority."
My question is:
"Why is the middle element of a sorted array considered the majority element?"
Can someone please provide an explanation for this?
This particular problem requires:
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and that the majority element always exists in the array.
Below is the code snippet for the solution provided:
var majorityElement = function(nums) {
// sort the array and the middle is the majority
nums.sort((a,b) => a - b);
return nums[Math.floor(nums.length/2)];
};
console.log(majorityElement([3,2,3]))
console.log(majorityElement([2,2,1,1,1,2,2]))