๋ณธ๋ฌธ์œผ๋กœ ๋ฐ”๋กœ๊ฐ€๊ธฐ
728x90
๐Ÿ”—๋ฌธ์ œ ๋งํฌ
 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

 

๐Ÿ‘จ‍๐Ÿ’ปํ’€์ด ๊ณผ์ •

 

์ฒ˜์Œ์—๋Š” ์ˆซ์ž๊ฐ€ ์˜ค๋ฆ„์ฐจ์ˆœ ์ˆœ์„œ๋กœ ์•ˆ ๋“ค์–ด์˜ค๋Š” ์ค„ ์•Œ๊ณ , ์ •๋ ฌ์„ ํ•ด์คฌ์—ˆ๋Š”๋ฐ ์ž…๋ ฅ์ด ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ๋“ค์–ด์˜ค๋Š” ๊ฒƒ ๊ฐ™์•„ ํ•„์š” ์—†๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. <key, value> ์Œ์œผ๋กœ ์ €์žฅ๋˜๊ณ , ๊ฒ€์ƒ‰์— ์œ ๋ฆฌํ•œ ์ž๋ฃŒ๊ตฌ์กฐ์ธ STL์˜ map ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ์ด์šฉํ–ˆ์Šต๋‹ˆ๋‹ค.

#include <vector>
#include <map>
using namespace std;

template<typename T>
map<T, T>* CountNumbers(const vector<T>& array)
{
    map<T, T>* numbers = new map<T, T>();
    for (auto number : array)
    {
        auto itFind = numbers->find(number);
        if (itFind != numbers->end())   // ํ•ด๋‹น ์ˆซ์ž๊ฐ€ ์ด๋ฏธ ์กด์žฌํ•˜๋ฉด ๊ฐœ์ˆ˜++
        {
            itFind->second++;
            continue;
        }

        numbers->insert(make_pair(number, 1));  // ํ•ด๋‹น ์ˆซ์ž๊ฐ€ ์—†์œผ๋ฉด 1๊ฐœ๋กœ ๋ฐ์ดํ„ฐ ๋“ฑ๋ก
    }
    return numbers;
}

 

์œ„ ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด์คฌ๊ณ , ํ•ด๋‹น ํ•จ์ˆ˜๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ์ตœ๋นˆ๊ฐ’๊ณผ ์ค‘๋ณต ์—ฌ๋ถ€๋ฅผ ์ฒดํฌํ•˜์˜€์Šต๋‹ˆ๋‹ค.

int solution(vector<int> array) {
    map<int, int>* numbers = CountNumbers(array);
    bool isduplicated = false;
    int currentCount = 0;
    int answer = 0;

    for (const auto data : *numbers)
    {
        if (data.second > currentCount) {
            answer = data.first;
            currentCount = data.second;
            isduplicated = false;
            continue;
        }

        if (data.second == currentCount && !isduplicated) {
            isduplicated = true;
        }
    }

    if (isduplicated)
        return -1;
    return answer;
}

 

์‹คํ–‰ ๊ฒฐ๊ณผ

 

728x90
๋ฐ˜์‘ํ˜•