본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 1394. Find Lucky Integer in an Array

반응형

https://leetcode.com/problems/find-lucky-integer-in-an-array/description/

 

Find Lucky Integer in an Array - LeetCode

Can you solve this real interview question? Find Lucky Integer in an Array - Given an array of integers arr, a lucky integer is an integer that has a frequency in the array equal to its value. Return the largest lucky integer in the array. If there is no l

leetcode.com

간단 구현 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

1. 숫자와 빈도수를 key, value형태로 저장할 map freqMap을 선언 후 arr의 원소를 순회하며 맞는 값을 저장해줍니다.2. 정답변수 maxLuckyNum를 선언 후 -1로 초기화해줍니다.

📔 풀이과정

freqMap의 원소를 수행하며 luckyNum을 찾고 찾았다면 maxLuckyNum에 최댓값을 저장해줍니다.

📔 정답 출력 | 반환

maxLuckyNum를 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    int findLucky(vector<int>& arr) {
        map <int, int> freqMap;
        for(auto a : arr) {
            freqMap[a]++;
        }
        int maxLuckyNum = -1;
        for(auto f : freqMap) {
            int num = f.first;
            int numFreq = f.second;
            if(num != numFreq) continue;
            maxLuckyNum = max(maxLuckyNum, num);
        }
        return maxLuckyNum;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.