星空网 > 软件开发 > Java

[LeetCode] 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.

 

     这道题其实可以用比较取巧的方法做。因为在这里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];  }}

     当然了还有比较常规的,老实按照loop来计算的。这个思路就很简单了。代码如下。

public class Solution {  public int majorityElement(int[] num) {    if(num.length==1){      return num[0];    }     Arrays.sort(num);     int test=num[0];    int count=1;    for(int i=1; i<num.length; i++){      if(num[i] == test){        count++;        if(count > num.length/2)         return num[i];      }else{        count=1;        test = num[i];      }    }     return 0;  }}

 




原标题:[LeetCode] Majority Element

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流