Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode题解:169. 多数元素,排序,JavaScript,详细注释 #223

Open
chencl1986 opened this issue Nov 15, 2020 · 0 comments
Open

Comments

@chencl1986
Copy link
Owner

原题链接:https://leetcode-cn.com/problems/majority-element/

解题思路:

  1. 如果一个数占据数组超过n/2的数量,那么它排序后,无论在数组中的哪个位置,必然会数组的中间位置。
  2. 因此只需要返回排序后的中间值即可。
/**
 * @param {number[]} nums
 * @return {number}
 */
var majorityElement = function (nums) {
  // 将数组排序
  nums.sort((a, b) => a - b);
  // 查找中间项的索引
  const middleIndex = Math.floor(nums.length / 2);
  // 中间项的值即为多数元素
  return nums[middleIndex];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant