首页 > 其他 > 详细

leetcode-158周赛-5225-最大相等频率

时间:2019-10-14 11:33:15      阅读:79      评论:0      收藏:0      [点我收藏+]

题目描述:

技术分享图片

 

 方法:

class Solution(object):
    def maxEqualFreq(self, A):
        count = collections.Counter()
        freqs = collections.Counter()
        ans = 1
        for i, x in enumerate(A):
            count[x] += 1
            c = count[x]
            freqs[c] += 1
            if c-1 > 0: freqs[c-1] -= 1
            if freqs[c-1] == 0:
                del freqs[c-1]
            L = len(freqs)
            #print freqs
            if L <= 2:
                if L <= 1:
                    k, = freqs.keys()
                    fk = freqs[k]
                    #print ‘.‘, i+1, ‘;‘, k, freqs[k]
                    if k == 1 or fk == 1:
                        ans = i + 1
                else:
                    a, b = freqs.keys()
                    fa, fb = freqs[a], freqs[b]
                    # remove a
                    #print i+1,a,fa,‘;‘,b,fb
                    if fa-1 == 0 and a-1 == b:
                        ans = i + 1
                    if fb-1 == 0 and b-1 == a:
                        ans = i + 1
                    if a == 1 and fa == 1 or b == 1 and fb == 1:
                        ans = i + 1
        return ans

另:倒推

from collections import Counter
class Solution(object):
    def maxEqualFreq(self, nums):
        cnt = Counter(nums)
        l = len(cnt)
        s = n = len(nums)
        if n==1:
            return 1
        for i in range(n-1,0,-1):
            if (s-1) % l == 0:
                k = (s-1)//l
                if all(x==k or x==k+1 for x in cnt.values()):
                    return i+1
            if l!=1 and (s-1) % (l-1) == 0:
                k = (s-1)//(l-1)
                if all(x==k or x==1 for x in cnt.values()):
                    return i+1
            num = nums[i]
            s-=1
            cnt[num]-=1
            if cnt[num]==0:
                del cnt[num]
                l-=1
        return 1

 

leetcode-158周赛-5225-最大相等频率

原文:https://www.cnblogs.com/oldby/p/11670231.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!