Majority Element 主要的元素

来源:互联网 发布:十块吧淘宝优站 编辑:程序博客网 时间:2024/05/16 07:27

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.

方法1:

直接排序,中间的元素一定是出现次数最多的元素。

    public int majorityElement1(int[] nums) {        Arrays.sort(nums);        return nums[nums.length / 2];    }

运行时间:


方法2:

排序的方式,时间复杂度是O (NlogN)

下面介绍一个时间复杂度为O (N)的算法。

    // moore voting algorithm    public int majorityElement2(int[] nums) {        int pre = nums[0];        int count = 1;        for (int num : nums) {            if (num == pre) {                count++;            } else {                count--;            }            if (count == 0) {                pre = num;                count = 1;            }        }        return pre;    }

运行时间:


虽然最后时间差不多。

参考资料:

https://leetcode.com/discuss/24971/o-n-time-o-1-space-fastest-solution

1 0