Does the solution satisfy the space and time condition? Why is it so slow ?(500ms)


  • 0
    H
    public List<Integer> majorityElement(int[] nums) {
    	List<Integer> result = new ArrayList<>();
    	int size = nums.length;
    	int count;
    	Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    	for(int i=0; i<size; i++) {
    		if (map.containsKey(nums[i])) {
    			count = map.get(nums[i]) + 1;
    			map.put(nums[i], count);
    		} else {
    			count = 1;
    			map.put(nums[i], count);
    		}
    		if (count*3 > size && (count-1)*3 <= size)
    			result.add(nums[i]);
    	}
    	return result;
    }

  • 3
    H

    I think the space complexity is O(n)


Log in to reply
 

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