My O(n) 14 ms JAVA accepted solution (Beats 99.33%)


  • 0
    Z
    class Solution {
        public List<Integer> topKFrequent(int[] nums, int k) {
            List<Integer> list = new ArrayList<>();
            int max = Integer.MIN_VALUE, min = Integer.MAX_VALUE;
            for (int i = 0; i < nums.length; i++) {
            	max = Math.max(nums[i], max);
            	min = Math.min(nums[i], min);
            }
            int[] res = new int[max - min + 1];
            for (int i = 0; i < nums.length; i++) {
            	res[nums[i] - min]++;
            }
            for (int i = 0; i < k; i++) {
            	int ran = rank(res);
            	res[ran] = 0;
            	list.add(ran + min);
            }
            return list;
        }
        private int rank(int[] res) {
        	int max = 0, index = 0;
        	for (int i = 0; i < res.length; i++) {
        		if (res[i] > max) {
        			index = i;
        			max = res[i];
        		}
        	}
            return index;
        }
    }
    

Log in to reply
 

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