public int[] topKFrequent(int[] nums, int k) {
if (nums == null || nums.length == 0 || k <= 0) return new int[0];
Map<Integer, Integer> freqMap = new HashMap<>();
for (int currNum : nums) freqMap.put(currNum, freqMap.getOrDefault(currNum, 0)+1);
I don't understand what the .getOrDefault(currNum, 0)+1); is doing, but it seems to calculate the frequency properly. I'd like some clearance on this method please and how exactly it's working.
Reference: https://www.geeksforgeeks.org/hashmap-getordefaultkey-defaultvalue-method-in-java-with-examples/
So, by using that method, first, you're trying to get key's value from the freqMap. If you can find it in map, then you're adding 1 to it and putting it back to freqMap. So, that means that you encountered this key before. Otherwise, that method ,
.getOrDefault(), returns you default value, which is 0, then you're adding 1 to it since you encountered it recently. And putting that value 1 to back to map. So, in the future, when you see that key again, you'll get it's value 1 that you added to the map before, will increase it to 2, and will put it back into the map.