LeetCode 1224 Maximum Equal Frequency (hash)

Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences.

If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).

Example 1:

Input: nums = [2,2,1,1,5,3,3,5]
Output: 7
Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice.

Example 2:

Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5]
Output: 13

Example 3:

Input: nums = [1,1,1,2,2,2]
Output: 5

Example 4:

Input: nums = [10,2,8,9,3,8,1,5,2,3,7,6]
Output: 8

Constraints:

  • 2 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^5

题目链接:https://leetcode.com/problems/maximum-equal-frequency/

题目大意:给一个数组,求一个最长的前缀,使得该前缀删除一个数字后其余数字频数相同

题目分析:这题是hard。。。?cnt数组记录数字出现次数,freq数组记录cnt的频数,如果满足条件必然只有两种情况:

一.待删除数字在当前前缀中,比如1 1 3 2 2

二.当前前缀满足频数要求,需删除后面的数字,比如1 1 2 2 3

分别判断下即可

5ms,时间击败95%

class Solution {
    public int maxEqualFreq(int[] nums) {
        int[] cnt = new int[100005];
        int[] freq = new int[100005];
        int ans = 1, n = nums.length;
        for (int i = 0; i < n; i++) {
            cnt[nums[i]]++;
            int numCount = cnt[nums[i]];
            freq[numCount]++;
            // System.out.println("freq[" + numCount + "] = " + freq[numCount] + " i = " + i);
            if (freq[numCount] * numCount == i) {
                ans = Math.max(ans, i + 1);
            } else if (freq[numCount] * numCount == i + 1 && i < n - 1) {
                ans = Math.max(ans, i + 2);
            }
        }
        return ans;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值