Javascript-为什么排序数组中的中间元素是多数元素?

我正在用leetcode执行this question.

我看到了我无法理解的解决方案

它说:“排序数组,中间居多”

我想问的是

“Why the middle element in a sorted array is the majority element?”

有人可以解释一下吗?

这个问题的要求:

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 the majority element always exist in the array.

这是答案的代码:

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,1,2]))
最佳答案
假设输入数组具有多数元素,则它将在数组中至少出现(n / 2)1次.如果多数元素是数组中的最小数字,则排序后的数组将类似于:

MMMMXX
  ^^ mid (even)

要么

MMMMMXXX
    ^ mid (odd)

其中M是多数元素,X表示任何其他元素.如您所见,M将始终落在数组的中间.如果多数元素是数组中的最高数字,则它将类似于:

XXMMMM
  ^^ mid (even)

要么

XXXMMMM
    ^ mid (odd)

M仍在中间.

如果M既不是数组中的最高元素也不是数组中的最低元素,那么无论您如何尝试移动范围,排序后的数组仍将在中间保留M:

XXMMMM
XMMMMX
MMMMXX
  ^^

要么

XXXMMMM
XXMMMMX
XMMMMXX
MMMMXXX
   ^

这些示例仅适用于长度为6和7的数组,但相同的想法适用于任何大小的数组.

相关文章

kindeditor4.x代码高亮功能默认使用的是prettify插件,prett...
这一篇我将介绍如何让kindeditor4.x整合SyntaxHighlighter代...
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面
如何用js控制图片放大缩小