LeetCode 1394. Find the lucky number in the array

LeetCode 1394. Find the lucky number in the array

I don't know where I am going, but I am already on my way!
Time is hurried, although I have never met, but I met Yusi, it is really a great fate, thank you for your visit!
  • Question :
    In an integer array, if the frequency of occurrence of an integer is equal to its numerical value, we call this integer a "lucky number".
    Give you an array of integers arr, please find out and return a lucky number from it.
    • If there are multiple array lucky number, simply return the biggest one.
    • If there is no lucky number in the array, -1 is returned .
  • Example :
示例 1 :
输入:arr = [2,2,3,4]
输出:2
解释:数组中唯一的幸运数是 2 ,因为数值 2 的出现频次也是 2 。
示例 2 :
输入:arr = [1,2,2,3,3,3]
输出:3
解释:1、2 以及 3 都是幸运数,只需要返回其中最大的 3 。
示例 3 :
输入:arr = [2,2,2,3,3]
输出:-1
解释:数组中不存在幸运数。
示例 4 :
输入:arr = [5]
输出:-1
示例 5 :
输入:arr = [7,7,7,7,7,7,7]
输出:7
  • Tips :
    • 1 <= arr.length <= 500
    • 1 <= arr[i] <= 500
  • Code 1:
class Solution:
    def findLucky(self, arr: List[int]) -> int:
        result = []
        for i in range(len(arr)):
            if arr.count(arr[i]) == arr[i]:
                result.append(arr[i])
        if result == []:
            return -1
        return max(result)
# 执行用时 :160 ms, 在所有 Python3 提交中击败了6.10%的用户
# 内存消耗 :13.7 MB, 在所有 Python3 提交中击败了100.00%的用户
  • Algorithm description:
    Count the number of occurrences of the current element arr[i]in the list . If the value of the element is equal to the number of occurrences, store the element in the list and return the largest element in the list .arrarr.count(arr[i])resultresult

Guess you like

Origin blog.csdn.net/qq_34331113/article/details/106672812