Middle-题目89:229. Majority Element II

来源:互联网 发布:张兆艺淘宝店 编辑:程序博客网 时间:2024/06/05 01:50

题目原文:
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.
题目大意:
给出一个数组,寻找所有出现次数超过[n/3]的元素。要求O(n)时间及O(1)空间复杂度。
题目分析:
方法一(朴素解法,最坏O(n)空间复杂度)用HashMap统计每个元素出现次数,返回超过n/3的。
方法二:类似于前面的寻找唯一主元素(Easy-题目11),这次因为出现次数超过n/3,所以至多有2个。那么维护两个重复次数c1,c2就可以得到出现次数最多的前两个元素,再扫描一遍看看是否超过n/3即可。
源码:(language:java)
方法一:

public class Solution {    public List<Integer> majorityElement(int[] nums) {        List<Integer> list = new ArrayList<Integer>();        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();        for(int num:nums) {            if(map.containsKey(num)) {                int count = map.get(num);                count++;                map.put(num,count);                if(count > nums.length/3 && !list.contains(num))                    list.add(num);            }            else {                map.put(num, 1);                if(nums.length < 3)                    list.add(num);            }        }        return list;    }}

方法二:

public class Solution {    public List<Integer> majorityElement(int[] nums) {        // 1, 2        List<Integer> res = new ArrayList<>();        if(nums==null || nums.length==0) return res;        if(nums.length==1) {            res.add(nums[0]);            return res;        }        int m1 = nums[0];        int m2 = 0;        int c1 = 1;        int c2 = 0;        for(int i=1; i<nums.length; i++) {            int x = nums[i];            if(x==m1) ++c1;            else if(x==m2) ++c2;            else if(c1==0) {                m1 = x;                c1 = 1;            } else if(c2==0) {                m2 = x;                c2 = 1;            } else {                --c1; --c2;            }        }        c1 = 0; c2 = 0;        for(int i=0; i<nums.length; i++) {            if(m1 == nums[i]) ++c1;            else if(m2 == nums[i]) ++c2;        }        if(c1>nums.length/3) res.add(m1);        if(c2>nums.length/3) res.add(m2);        return res;    }}

成绩:
方法一:35ms,beats 5.75%,众数4ms,31.82%
方法二:5ms,beats 29.28%
Cmershen的碎碎念:
是否能进一步优化,使得只扫描一遍数组?因为我观察到还有约25%的提交代码做到3ms。

0 0
原创粉丝点击