首页 > 代码库 > 229. Majority Element II

229. Majority Element II

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.

思路:边扫边存边判断。比较naive的做法。

public class Solution {    public List<Integer> majorityElement(int[] nums) {        List<Integer> check=new ArrayList<Integer>();        if(nums.length==0)        {            return check;        }        Map<Integer,Integer> res=new HashMap<Integer,Integer>();        for(int i=0;i<nums.length;i++)        {            if(!res.containsKey(nums[i]))            {                res.put(nums[i],1);            }            else            {                res.put(nums[i],res.get(nums[i])+1);            }            if(!check.contains(nums[i]))            {            if(res.get(nums[i])>(nums.length/3))            {                check.add(nums[i]);            }            }        }        return check;            }}

 

229. Majority Element II