Leetcode229 Majority Element II

来源:互联网 发布:array push 二维数组 编辑:程序博客网 时间:2024/06/15 04:39

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 Solution229 {    public List<Integer> majorityElement(int[] nums) {        List<Integer> result = new ArrayList<Integer>();        Map<Integer,Integer> map = new HashMap<Integer,Integer>();        for (int i = 0; i < nums.length;i++) {            int cnt = 0;            if(map.containsKey(nums[i])) {                cnt = map.get(nums[i]).intValue()+1;            } else {                cnt=1;            }            map.put(nums[i],cnt);        }        int n = nums.length/3;        for (Integer key:map.keySet()) {            int cnt = map.get(key);            if(cnt > n) {                result.add(key);            }        }        return result;    }    public static void main(String[] args) {    }}


0 0
原创粉丝点击