[LeetCode Solutions] 3005. Count Elements With Maximum Frequency

Table of Contents

題目

You are given an array nums consisting of positive integers.

Return the total frequencies of elements in nums such that those elements all have the maximum frequency.

The frequency of an element is the number of occurrences of that element in the array.

Example 1:Input: nums = [1,2,2,3,1,4] Output: 4 Explanation: The elements 1 and 2 have a frequency of 2 which is the maximum frequency in the array. So the number of elements in the array with maximum frequency is 4.

Example 2:Input: nums = [1,2,3,4,5] Output: 5 Explanation: All elements of the array have a frequency of 1 which is the maximum. So the number of elements in the array with maximum frequency is 5.

意思是說給你一個正整數陣列,要你求出出現頻率最高的次數有幾個,然後返回總和。

例如:

example 1,1跟2都出現了兩次,有兩個,那我們就是2*2=4
example 2,因為都只出現了一次,有五個,那就是5



思路

我們可以用兩個map來做,第一個map是計算陣列元素的出現次數,第二個map是計算出現次數的map,再宣告一個變量來計算出現頻率最高的數字

以example 1來說的話,
我們的第一個map預期會長這樣 {1=2, 2=2, 3=1, 4=1}

第二個map由於1出現2次,2出現2次,則是會長這樣{1=2, 2=2}
然後計算出頻率最高的次數為2,有2次


解法

public int maxFrequencyElements(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        Map<Integer, Integer> countsMap = new HashMap<>();
        int maxFreq = 0; //出現頻率最高的數字

        for(int num:nums){
            int value = map.getOrDefault(num, 0)+1;
            map.put(num, value);
            
            int times = countsMap.getOrDefault(value, 0)+1;
            countsMap.put(value, times);
          
            maxFreq = Math.max(maxFreq, value);
        }
        int total = maxFreq * countsMap.get(maxFreq);

        return total;
    }

以下也提供用兩個for loop的解法

public int maxFrequencyElements(int[] nums) {
        Map<Integer, Integer> freqMap = new HashMap<>();
        int maxFreq = 0;
        for(var num : nums){
            freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
            maxFreq = Math.max(maxFreq, freqMap.get(num));
        }

        int maxFreqEleCnt = 0;
        for(var entry : freqMap.entrySet()){
            int currEleFreq = entry.getValue();
            if(currEleFreq == maxFreq){
                maxFreqEleCnt++;
            }
        }
        return maxFreq * maxFreqEleCnt;

    }

發佈留言