楼主: Myron2017
跳转到指定楼层
上一主题 下一主题
收起左侧

刷题记录帖子

🔗
 楼主| Myron2017 昨天 10:18 | 只看该作者
全局:
LC. 3005. Count Elements With Maximum Frequency

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

我的解法,多变遍历
  1. class Solution:
  2.     def maxFrequencyElements(self, nums: List[int]) -> int:
  3.         freq = Counter(nums)
  4.         max_freq = max(freq.values())

  5.         ans = 0

  6.         for v in freq:
  7.             if freq[v] == max_freq:
  8.                 ans += max_freq
  9.         
  10.         return ans
  11.         
复制代码
优化的同样思路的写法
  1. from collections import Counter
  2. from typing import List

  3. class Solution:
  4.     def maxFrequencyElements(self, nums: List[int]) -> int:
  5.         freq = Counter(nums)
  6.         max_freq = max(freq.values())
  7.         
  8.         # 生成器表达式:遍历所有频次,如果等于最大频次,就累加
  9.         return sum(f for f in freq.values() if f == max_freq)
复制代码
更加优化的写法, 一次遍历!

核心思路:在遍历数组、累加频率的同时,动态维护当前的 max_freq 和 ans。

如果发现某个数字的频率 大于 当前的 max_freq,说明之前的 ans 都作废了,我们要更新 max_freq,并且把 ans 重置为当前频率。

如果发现某个数字的频率 等于 当前的 max_freq,说明它也是最大频率的候选人,把它的频率累加到 ans 中。

一次遍历代码实现
  1. class Solution:
  2.     def maxFrequencyElements(self, nums: List[int]) -> int:
  3.         freq = {}
  4.         max_freq = 0
  5.         ans = 0
  6.         
  7.         for num in nums:
  8.             # 1. 更新当前数字的频次
  9.             freq[num] = freq.get(num, 0) + 1
  10.             cur_freq = freq[num]
  11.             
  12.             # 2. 动态维护最大频次和答案
  13.             if cur_freq > max_freq:
  14.                 max_freq = cur_freq
  15.                 ans = cur_freq       # 出现更大的频次,之前的 ans 作废,重新洗牌
  16.             elif cur_freq == max_freq:
  17.                 ans += cur_freq      # 和当前最大频次一样,累加到 ans 中
  18.                
  19.         return ans
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表