LeetCode: Find Lucky Integer in an Array
Question
Given an array of integers arr, a lucky integer is an integer which has a frequency in the array equal to its value.
Return a lucky integer in the array. If there are multiple lucky integers return the largest of them. If there is no lucky integer return -1.
Solution #1
def find_lucky(arr)
dict = Hash.new(0)
arr.each do |element|
dict[element] += 1
end
dict.delete_if { |k, v| k != v }
return -1 if dict.empty?
dict.values.max
end
Comments