返回介绍

solution / 3000-3099 / 3005.Count Elements With Maximum Frequency / README_EN

发布于 2024-06-17 01:02:58 字数 3772 浏览 0 评论 0 收藏 0

3005. Count Elements With Maximum Frequency

中文文档

Description

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.

 

Constraints:

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

Solutions

Solution 1: Counting

We can use a hash table or array $cnt$ to record the occurrence of each element.

Then we traverse $cnt$ to find the element with the most occurrences, and let its occurrence be $mx$. We sum up the occurrences of elements that appear $mx$ times, which is the answer.

The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $nums$.

class Solution:
  def maxFrequencyElements(self, nums: List[int]) -> int:
    cnt = Counter(nums)
    mx = max(cnt.values())
    return sum(x for x in cnt.values() if x == mx)
class Solution {
  public int maxFrequencyElements(int[] nums) {
    int[] cnt = new int[101];
    for (int x : nums) {
      ++cnt[x];
    }
    int ans = 0, mx = -1;
    for (int x : cnt) {
      if (mx < x) {
        mx = x;
        ans = x;
      } else if (mx == x) {
        ans += x;
      }
    }
    return ans;
  }
}
class Solution {
public:
  int maxFrequencyElements(vector<int>& nums) {
    int cnt[101]{};
    for (int x : nums) {
      ++cnt[x];
    }
    int ans = 0, mx = -1;
    for (int x : cnt) {
      if (mx < x) {
        mx = x;
        ans = x;
      } else if (mx == x) {
        ans += x;
      }
    }
    return ans;
  }
};
func maxFrequencyElements(nums []int) (ans int) {
  cnt := [101]int{}
  for _, x := range nums {
    cnt[x]++
  }
  mx := -1
  for _, x := range cnt {
    if mx < x {
      mx, ans = x, x
    } else if mx == x {
      ans += x
    }
  }
  return
}
function maxFrequencyElements(nums: number[]): number {
  const cnt: number[] = Array(101).fill(0);
  for (const x of nums) {
    ++cnt[x];
  }
  let [ans, mx] = [0, -1];
  for (const x of cnt) {
    if (mx < x) {
      mx = x;
      ans = x;
    } else if (mx === x) {
      ans += x;
    }
  }
  return ans;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文