[LeetCode] 1394. Find the lucky number in the array (C++)

1 topic description

In an integer array, if the frequency of occurrence of an integer is equal to its numerical value, we call the integer a "lucky number".
Give you an integer array arr, please find out 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.

2 Example description

2.1 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.

2.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.

2.3 Example 3

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

2.4 Example 4

Input: arr = [5]
Output: -1

2.5 Example 5

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

3 Problem solving tips

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

4 Problem-solving ideas

Solve with violence.

5 Detailed source code (C++)

class Solution {
    
    
public:
    int findLucky(vector<int>& arr) {
    
    
        int res[501] = {
    
     0 } ;
        sort( arr.begin() , arr.end() ) ;
        for ( int i = 0 ; i < arr.size() ; i ++ )
        {
    
    
            res[arr[i]] ++ ;
        }
        for ( int i = 500 ; i > 0 ; i -- )
        {
    
    
            if ( res[i] == i )
            {
    
    
                return i ;
            }
        }
        return -1 ;
    }
};

6 Wrong ideas

The number of 0 positions cannot be guaranteed here.

7 Error code (C++)

class Solution {
    
    
public:
    int findLucky(vector<int>& arr) {
    
    
        int res[501] = {
    
     0 } ;
        int luck_num = -1 ;
        sort( arr.begin() , arr.end() ) ;
        for ( int i = 0 ; i < arr.size() ; i ++ )
        {
    
    
            res[arr[i]] ++ ;
        }
        for ( int i = 0 ; i < 500 ; i -- )
        {
    
    
            if ( res[i] == i )
            {
    
    
                luck_num = i ;
            }
        }
        return luck_num ;
    }
};

Guess you like

Origin blog.csdn.net/Gyangxixi/article/details/114314493