LC 1394. Find Lucky Integer in an Array

Nilanjan Deb · April 5, 2020

This is my CPP solution.

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


Dicussion Forum