其他分享
首页 > 其他分享> > 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

 

标签:周赛,cnt,return,nums,158,Counter,freqs,5225,num
来源: https://www.cnblogs.com/oldby/p/11670231.html