Simple java solution


  • -7
    L
    public class Solution {
        public List<Integer> majorityElement(int[] nums) {
            List<Integer> ret = new ArrayList<Integer>();
            int pong = (int) Math.round(nums.length / 3 + 0.5);
            Map<Integer, Integer> map = new HashMap<Integer, Integer>();
            for (int i : nums) {
                if (map.containsKey(i)) {
                    int count = map.get(i) + 1;
                    if (count == pong) {
                        ret.add(i);
                    }
                    map.put(i, count);
                    continue;
                }
                map.put(i, 1);
                if (pong == 1) {
                    ret.add(i);
                }
            }
            return ret;
        }
    }

  • 1
    H

    Your solution doesn't run in O(1) space!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.