我在LeetCode做这道题,看到了一种我理解不了的解法。
解法是:"将数组排序,数组中间的元素就是多数元素"。
我想问的是:
"为什么一个已排序数组的中间元素就是多数元素?"
有人可以解释一下吗?
这个问题的要求:
给定一个大小为n的数组,找到其中的多数元素。即出现次数超过 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且多数元素总是存在于数组中。
Here is the answer's code:
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]))