1394: Find-Lucky-Integer-in-an-Array
Easy
table of contents
Just sort the array first and iterate through the entirety of
arr
from back to front,
then simply returning the first number you see where its count
is equal to itself (since the array is sorted from
smallest to largest).
If there does not exist any number where this occurs, just return
-1
.
code
class Solution {
public:
int findLucky(vector<int>& arr) {
(arr.begin(), arr.end());
sort
int count = 1;
int curr = arr.back();
for (int i = arr.size()-2; i >= 0; --i) {
if (curr == arr[i]) {
++count;
} else {
if (count == curr) {
return curr;
}
= arr[i];
curr = 1;
count }
}
if (count == curr) {
return curr;
}
return -1;
}
};