[LeetCode题解]——169 Majority Element

[LeetCode题解]169 Majority Element

思路01

1.用最简单的方法。先用Arrays的sort方法把数组排序,再返回数组的中间的数。
时间复杂度 O(NlogN) 空间复杂度 O(1)。 

public class MajorityElement01 {
    public static int majorityElement(int[] nums){
        if (nums.length == 0 || nums == null)
            return 0;
        Arrays.sort(nums);
        return nums[nums.length / 2] ;
    }
}

思路02

2.哈希表法。把数组的每个数值和该数值的出现次数分别以键值对的形式存入哈希表中。当某数出
现次数大于数组的元素个数时,返回该数字。
时间复杂度 O(N) 空间复杂度 O(N)

public class MajorityElement02 {
    public static int majorityElement(int[] nums){
        if (nums.length == 0 || nums == null)
            return 0;
        HashMap<Integer,Integer> map = new HashMap<Integer, Integer>();
        int res = 0;
        for (int i = 0; i < nums.length ; i++) {
            if (!map.containsKey(nums[i]))
                map.put(nums[i],1);
            else
                map.put(nums[i],map.get(nums[i]) + 1);
            if (map.get(nums[i]) > nums.length / 2){
                res = nums[i];
                break;
            }
        }
        return res;
    }
}

思路03

3.Moore投票算法。是由德克萨斯大学的Robert S. Boyer教授和J Strother Moore教授发明的。该算法的主要思想是假设e是出现次数大于n/2的数字,那么将所有非e的数字和e成对地两两相消,最后剩下来的数字绝对是e.
过程:初始化最终返回值res为num[0],计数count为0.从左往右逐个遍历数组元素,如果与num[0]相等,则count加一。否则count减一。当count为0时,把res赋值为num[i+1].遍历结束后返回res.
时间复杂度 O(N) 空间复杂度 O(1)

public class MajorityElement03 {
    public static int majorityElement(int[] nums){
        if (nums.length == 0 || nums == null)
            return 0;
        int res = nums[0];int count = 1;
        for (int i = 1; i < nums.length ; i++) {
            if (res == nums[i])
                count++;
            else
                count--;
            if (count == 0)
                res = nums[i + 1];
            continue;
        }
        return res;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值