본문 바로가기
알고리즘 풀이

240308 LeetCode 문제 풀이

by 미노킴 2024. 3. 9.

3005. Count Elements With Maximum Frequency

https://leetcode.com/problems/count-elements-with-maximum-frequency/description/?envType=daily-question&envId=2024-03-08

 

1) 문제 설명

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.

 

2) 제한 사항

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 100

 

3) 도전 과제

X

 

4) 풀이

배열을 한번만 순회하고 싶었기에 Map과 새로운 배열을 이용하여 풀었다.

 

Map으로 각 값의 빈도수를 기록하며 최대 빈도수를 같이 기록하였다. 새 배열에는 빈도수의 갯수를 기록하였다.

 

5) 소스 코드 및 결과

import java.util.HashMap;

class Solution {
    public int maxFrequencyElements(int[] nums) {
        HashMap<Integer, Integer> map = new HashMap<>();

        int[] array = new int[nums.length];
        int max = 0;

        for(int i : nums){
            if(map.get(i)==null){
                map.put(i,1);
                array[0]++;
                max = Math.max(max,1);
                continue;
            };

            Integer count = map.get(i);
            map.put(i, count+1);
            max = Math.max(max, count+1);
            array[count]++;
        }

        return max * array[max-1];
    }
}

6) 다른 사람의 풀이

class Solution {
    public int maxFrequencyElements(int[] nums) {
        int[] freq = new int[101];

        for(int i = 0; i < nums.length; i++){
            freq[nums[i]]++;
        }

        int temp = 0;
        int c = 0;
        for(int i = 1; i < freq.length; i++){
            if(freq[i] == temp){
                c += freq[i];
            }
            else if(freq[i] > temp){
                temp = freq[i];
                c = freq[i];
            }
        }
        return c;
    }
}
 

'알고리즘 풀이' 카테고리의 다른 글

240313 LeetCode 문제 풀이  (0) 2024.03.13
240311 LeetCode 문제 풀이  (0) 2024.03.11
240306 LeetCode 문제 풀이  (0) 2024.03.06
231209 LeetCode 문제 풀이  (0) 2023.12.09
231201 LeetCode 문제 풀이  (0) 2023.12.01