Leetcode腾讯精选练习38 求众数

mac2022-06-30  27

原题Leetcode 169 点击跳转 给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且给定的数组总是存在众数。

示例 1:

输入: [3,2,3] 输出: 3

示例2:

输入: [2,2,1,1,1,2,2] 输出: 2

1.排序输出 利用数组排序后众数在数组的n/2处的性质,先对数组进行排序,然后返回n/2处的值即可。这里直接用内置函数排序即可。

public class Solution { public int MajorityElement(int[] nums) { Array.Sort(nums); return nums[nums.Length/2]; } }

最新回复(0)