[LeetCode]229. Majority Element II

来源:互联网 发布:昆明网络推广外包公司 编辑:程序博客网 时间:2024/06/05 11:04

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.

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


0 0
原创粉丝点击