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

题目描述:

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

 

 方法:

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

 

上一篇:世界上第一个便便数据库需要您的帮助!【智能快讯】


下一篇:前端每日实战:158# 视频演示如何用纯 CSS 创作一个雨伞 toggle 控件