Find the lucky number in the array [JavaScript]

Find the lucky number in the array

In an integer array, if the frequency of occurrence of an integer is equal to its value, we call the integer a "lucky number".
Give you an integer array arr, please find and return a lucky number from it.

If there are multiple lucky numbers in the array, just return the largest one.
If there is no lucky number in the array, -1 is returned.
Example 1:

Input: arr = [2,2,3,4]
Output: 2
Explanation: The only lucky number in the array is 2, because the frequency of occurrence of the value 2 is also 2.
Example 2:

Input: arr = [1,2,2,3,3,3]
Output: 3
Explanation: 1, 2 and 3 are all lucky numbers, only the largest 3 of them needs to be returned.
Example 3:

Input: arr = [2,2,2,3,3]
Output: -1
Explanation: There is no lucky number in the array.
Example 4:

Input: arr = [5]
Output: -1
Example 5:

Input: arr = [7,7,7,7,7,7,7]
Output: 7

prompt:

1 <= arr.length <= 500
1 <= arr[i] <= 500

Source: LeetCode
Link: https://leetcode-cn.com/problems/find-lucky-integer-in-an-array

The scheduled time was good. I got up at 10.30 for the weekly competition. But I overslept. When I woke up, it was more than 11.30. As a little rookie, I read the first question. (I guess I can only make the first One question, haha). I think the idea of ​​this question is relatively simple. Since we want to find the largest one, use sort to sort it first, and then find the first one. The same is true. If not, return -1.
code show as below:

/**
 * @param {number[]} arr
 * @return {number}
 */
var findLucky = function(arr) {
    
    
    let lucky = [], currentValue
    arr = arr.sort((a, b) => b - a)
    for (let i = 0; i < arr.length; i++) {
    
    
        currentValue = arr[i]//一次遍历获取当前的值
        let index = 0
        for (let j = 0; j < arr.length; j++) {
    
    
            if (arr[j] === currentValue) {
    
    //二次遍历计算与当前值相等的数量
                index++
            }
        }
        if (currentValue === index) {
    
    
            lucky.push(currentValue)//如果相等推入数组中
            index = 0
        }
    }
    return lucky.length ? lucky[lucky.length - 1] : -1//返回数组第一个值即可
};

Guess you like

Origin blog.csdn.net/weixin_42345596/article/details/105198244