Simple Java Solution


  • 0
    E

    Here is my solution, get each item index in the list and insert. Luckily, it works.

        private Map<Integer, Integer> map = new HashMap();
        public List<Integer> topKFrequent(int[] nums, int k) {
            List<Integer> list = new ArrayList<>();
            for (int i : nums) {
                if (!map.containsKey(i))
                    map.put(i, 1);
                else
                    map.put(i, map.get(i) + 1);
                    
                int index = get(list, i);
                if (index < k)
                    list.add(index, i);
                if (list.size() > k)
                    list.remove(list.size() - 1);
            }
            
            return list;
        }
        
        private int get(List<Integer> list, int i) {
            if (list.contains(i)) list.remove((Integer)i);
            if (list.size() == 0 || map.get(list.get(0)) < map.get(i)) return 0;
            if (map.get(list.get(list.size() - 1)) > map.get(i)) return list.size();
            
            int left = 0, right = list.size() - 1;
            while (left < right - 1) {
                int mid = (left + right) >> 1;
                //if (list.get(mid) == i) return mid;
                if (map.get(list.get(mid)) == map.get(i)) return mid;
                else if (map.get(list.get(mid)) > map.get(i)) left = mid;
                else right = mid;
            }
            
            return right;
        }
    }

Log in to reply
 

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