博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
主元素 Majority Element
阅读量:7026 次
发布时间:2019-06-28

本文共 1998 字,大约阅读时间需要 6 分钟。

  hot3.png

问题:

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.

Credits:

Special thanks to  for adding this problem and creating all test cases.

解决:

①我首先想到了将数组排序,然后记录每一个数值出现的次数,满足大于N/2的返回即可。耗时6ms。

public class Solution {

    public int majorityElement(int[] nums) {//出现次数大于n/2
        int count = 1; 
        int n = nums.length;
        int majority = 0;
        Arrays.sort(nums);
        if(nums.length == 1) return nums[0];
        for (int i = 1;i < nums.length ;i ++ ) {
            if (nums[i] == nums[i - 1]) {
                count ++;
                if(count > n / 2){
                    majority = nums[i];
                    break;
                }
            }else{
                count = 1;
            }       
        }
        return majority;
    }
}

Moore voting algorithm--每找出两个不同的element,就成对删除即count --,最终剩下的一定就是所求的。时间复杂度:O(n)。耗时3ms。

public class Solution {

    public int majorityElement(int[] nums) {
        int count = 0;
        int majority = 0;
        for (int i = 0;i < nums.length ;i ++ ) {
            if(count == 0){
                majority = nums[i];
                count ++;
            }else if(nums[i] == majority){
                count ++;
            }else{
                count --;
            }
        }
        return majority;
    }
}

③leetcode中建议了很多解法:

第一种是Brute force solution,时间复杂度为O(n2),顾名思义,遍历数组,依次判断每个元素是否为多数元素。

第二种是Hash table,时间复杂度为O(n),空间复杂度也为(n),对数组中的每个元素计数,大于⌊n/2⌋时即为所求结果。

第三种是Sorting,时间复杂度为O(nlogn),找到第n/2个元素即可。

第四种是Randomization,平均时间复杂度为O(n),最坏情况为无穷大。随机选一个元素,判断其是否为多数元素。由于选中多数元素的概率大于1/2,尝试次数的期望<2。

class Solution {public:    int majorityElement(vector
& nums) { int size = nums.size(); while (true) { int r = nums[rand() % size]; int count = 0; for (int i = 0; i < size; i++) { if (r == nums[i]) { count++; } } if (count > size >> 1) { return r; } } }};

第五种是Divide and conquer,时间复杂度为O(nlogn),将数组分成两半,分别递归查找这两部分的多数元素,若两者相同,则为多数元素,若不同,则其中之一必为多数元素,判断其一即可。

第六种是Moore voting algorithm,时间复杂度为O(n),每找出两个不同的element,就成对删除即count --,最终剩下的一定就是所求的。

转载于:https://my.oschina.net/liyurong/blog/915707

你可能感兴趣的文章
BZOJ 1084 最大子矩阵
查看>>
2018杭电多校第三场1007(凸包,极角排序)
查看>>
django中orm的简单操作
查看>>
Mybatis知识(1)
查看>>
[CentOS] 7 不执行文件 /etc/rc.d/rc.local
查看>>
模态窗口的各个属性
查看>>
10.28 (上午) 开课一个月零二十四天 (数据访问)
查看>>
为什么你应该(从现在开始就)写博客
查看>>
小技巧积累
查看>>
Java JDBC链接Oracle数据库
查看>>
Moss2010 部署命令
查看>>
Git 操作分支
查看>>
Grid search in the tidyverse
查看>>
hdu 三部曲 Contestants Division
查看>>
day22——创建表、增加数据、查询数据
查看>>
css伪元素实现tootip提示框
查看>>
Python基础知识随手记
查看>>
bzoj 1191 [HNOI2006]超级英雄Hero——二分图匹配
查看>>
关于xshell无法连接到centos的问题
查看>>
关于函数指针的总结
查看>>