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

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

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

programmers.co.kr

 

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

 

์ฒ ์ˆ˜์™€ ๋™์ƒ์˜ ๊ฐ ํ† ํ•‘ ์ข…๋ฅ˜ ์ˆ˜๋งŒ ๊ฐ™์œผ๋ฉด ๋˜๊ธฐ์—, ์ค‘๋ณต์ด ๋˜์ง€ ์•Š๋Š” ์ž๋ฃŒ๊ตฌ์กฐ๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. ๋ฐ์ดํ„ฐ์˜ ๊ฐœ์ˆ˜๊ฐ€ ์ตœ๋Œ€ 1,000,000๊ฐœ์ด๊ธฐ ๋•Œ๋ฌธ์— ๊ฒ€์ƒ‰, ์‚ฝ์ž…, ์‚ญ์ œ์— ์ข‹์€ ํ•ด์‹œ(Hash)๋ฅผ ์“ฐ๊ธฐ๋กœ ํ–ˆ์Šต๋‹ˆ๋‹ค. Key-value ๊ตฌ์กฐ์ธ unordered_map๊ณผ Key ๊ตฌ์กฐ์ธ unordered_set์„ ์‚ฌ์šฉํ•˜์˜€์Šต๋‹ˆ๋‹ค.

 

์ „๋žต์€ ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.

  1. ์ €๋Š” ์ฒ˜์Œ์— ์ฒ ์ˆ˜์—๊ฒ ํ•œ ์กฐ๊ฐ๋„ ์—†๊ณ , ๋™์ƒ์ด ๋ชจ๋“  ์ผ€์ดํฌ ์กฐ๊ฐ์„ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ์ƒํƒœ๋กœ ์ถœ๋ฐœํ•ฉ๋‹ˆ๋‹ค.
    • topping์„ ์ˆœํšŒํ•˜๋ฉฐ, ๊ฐ ํ† ํ•‘์˜ ๊ฐœ์ˆ˜ ์นด์šดํŠธํ•˜์—ฌ ์ €์žฅ (unordered_map) \( \rightarrow \) ๋™์ƒ ๊บผ
  2. ๋‹ค์‹œ topping์„ ์ˆœํšŒํ•˜๋ฉฐ, ์ฒ ์ˆ˜์—๊ฒŒ ํ•œ ์กฐ๊ฐ์”ฉ ๋™์ƒ์ด ์–‘๋ณดํ•ด์ค๋‹ˆ๋‹ค.
    • ์ฒ ์ˆ˜๋Š” ํ† ํ•‘์˜ ๊ฐœ์ˆ˜๋Š” ํ•„์š” ์—†๊ณ , ์ข…๋ฅ˜ ์ •๋ณด๋งŒ ์žˆ์œผ๋ฉด ๋˜๊ธฐ์— unordered_set์„ ์‚ฌ์šฉ
    • ๋™์ƒ์ด ์ฒ ์ˆ˜์—๊ฒŒ ํ•œ ์กฐ๊ฐ ์–‘๋ณดํ–ˆ์œผ๋ฉด, ๋™์ƒ ๊บผ์—์„œ ํ•ด๋‹น ํ† ํ•‘ ๊ฐœ์ˆ˜ ํ•œ ์กฐ๊ฐ ๊ฐ์†Œ
      • ํ•ด๋‹น ํ† ํ•‘์„ ๋ชจ๋‘ ์–‘๋ณดํ•˜์—ฌ 0๊ฐœ๋ผ๋ฉด, key ์‚ญ์ œ
    • ์ฒ ์ˆ˜์˜ ํ† ํ•‘ ๊ฐœ์ˆ˜(unordered_set.size())์™€ ๋™์ƒ์˜ ํ† ํ•‘ ๊ฐœ์ˆ˜(unordered_map.size())๊ฐ€ ๊ฐ™์œผ๋ฉด answer + 1

 

โœ๏ธ์†Œ์Šค ์ฝ”๋“œ ๋ฐ ๊ฒฐ๊ณผ

#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;

int solution(vector<int> topping) {
    int answer = 0;
    unordered_map<int, int> youngerBrotherToppings;
    youngerBrotherToppings.reserve(topping.size());

    for (const auto i : topping)
        youngerBrotherToppings[i]++;

    unordered_set<int> olderBrotherToppings;
    olderBrotherToppings.reserve(topping.size());

    for (int i = 0; i < topping.size(); i++) {
        olderBrotherToppings.insert(topping[i]);
        auto toppingIt = youngerBrotherToppings.find(topping[i]);

        if (toppingIt == youngerBrotherToppings.end())
            continue;

        if (toppingIt->second > 0) {
            toppingIt->second--;

            if(toppingIt->second == 0)
                youngerBrotherToppings.erase(topping[i]);
        }

        if (olderBrotherToppings.size() == youngerBrotherToppings.size())
            answer++;
    }

    return answer;
}

 

์ œ์ถœ ๊ฒฐ๊ณผ

 

728x90
๋ฐ˜์‘ํ˜•