Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 &rf ...
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.
这道题其实可以用比较取巧的方法做。因为在这里marjority element的定义是整个数列中至少一半的数字都是它,所以当我们sorting了整个数列,中间的那个数肯定是Marjority element。所以非常简单,考虑下length为1的特殊情况就可。代码如下。
public class Solution { public int majorityElement(int[] nums) { if(nums.length==1){ return nums[0]; } Arrays.sort(nums); return nums[nums.length/2]; }}
海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com
原标题:[LeetCode] Majority Element
关键词:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。