LeetCode #1394. Find Lucky Integer in an Array

题目

1394. Find Lucky Integer in an Array


解题方法

遍历数组计算每个数字的频率,存入字典,设置返回值rat=-1并遍历字典中的键,如果key - dic[key] == 0,则设置rat = max(rat, key),最后返回rat。
时间复杂度:O(n)
空间复杂度:O(n)


代码

class Solution:
    def findLucky(self, arr: List[int]) -> int:
        dic = {}
        for i in arr:
            if i not in dic:
                dic[i] = 1
            else:
                dic[i] += 1
        
        rat = -1
        for key in dic.keys():
            if not key - dic[key]:
                rat = max(rat, key)
        
        return rat
posted @ 2020-11-30 09:17  老鼠司令  阅读(40)  评论(0编辑  收藏  举报