[Programmers] Lv3. [์นด์นด์˜ค ์ธํ„ด] ๋ณด์„ ์‡ผํ•‘ | C++

2023. 10. 22. 12:12ใ†Coding Test/Programmers

๐Ÿ”—๋ฌธ์ œ ๋ณด๋Ÿฌ๊ฐ€๊ธฐ
 

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

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

programmers.co.kr

 

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

 

๋ฌธ์ œ๋ฅผ ๋ณด์ž๋งˆ์ž ์–‘ ์ชฝ์— ์ธ๋ฑ์Šค๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋Š” ๋ณ€์ˆ˜ 2๊ฐœ๋ฅผ ๋‘๊ณ  ๊ตฌ๊ฐ„์„ ์ค„์—ฌ๊ฐ€๋ฉฐ ๊ตฌํ•ด์•ผ๊ฒ ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ๋Š”๋ฐ, ์ด๊ฒŒ ํˆฌ ํฌ์ธํ„ฐ(Two pointer) ์•Œ๊ณ ๋ฆฌ์ฆ˜์ด๋”๊ตฐ์š”. ๋ชฐ๋ž์ง€๋งŒ ์ž์—ฐ์Šค๋Ÿฝ๊ฒŒ ์‚ฌ์šฉํ•˜๊ฒŒ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค..?

ํ’€์ด ๋ฐฉ์‹์€ ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.

 

  1. gems ๋ฐฐ์—ด์„ ์ˆœํšŒํ•˜๋ฉฐ ๋ณด์„์˜ ์ข…๋ฅ˜ ๊ฐœ์ˆ˜๋ฅผ ์•Œ์•„๋‚ธ๋‹ค.
  2. ์‹œ์ž‘ ์ธ๋ฑ์Šค(start)์™€ ๋ ์ธ๋ฑ์Šค(end) ๋ณ€์ˆ˜๋ฅผ ๊ฐ๊ฐ 0์œผ๋กœ ๋‘๊ณ , ๋ณด์„์˜ ์ข…๋ฅ˜ ๊ฐœ์ˆ˜๋ฅผ ๋‹ค ํฌํ•จํ•˜๋Š” ๊ตฌ๊ฐ„์ด ๋  ๋•Œ๊นŒ์ง€ end๋ฅผ ์ฆ๊ฐ€์‹œํ‚จ๋‹ค.
  3. ๋ณด์„์˜ ์ข…๋ฅ˜๋ฅผ ๋ชจ๋‘ ํฌํ•จํ•˜๋Š” ๊ฐ€์žฅ ์ž‘์€ ๊ตฌ๊ฐ„๊นŒ์ง€ ์‹œ์ž‘ ์ธ๋ฑ์Šค๋ฅผ ์ฆ๊ฐ€์‹œํ‚จ๋‹ค.
  4. ๊ทธ ๊ณผ์ •์—์„œ ๊ตฌ๊ฐ„, start, end ๊ฐ’์„ ๊ฐฑ์‹ ์‹œํ‚ค๋ฉฐ, ๋‹ค์Œ ์กฐ๊ฑด์„ ๋งŒ์กฑํ•  ๋•Œ๊นŒ์ง€ ์œ„ ๊ณผ์ •์„ ๋ฐ˜๋ณตํ•œ๋‹ค.
    • end == gems.size()์ธ๋ฐ, start > end๊ฐ€ ๋˜๋Š” ๊ฒฝ์šฐ
    • end == gems.size()์ธ๋ฐ, ๋ชจ๋“  ์ข…๋ฅ˜ ๊ฐœ์ˆ˜๋ฅผ ํฌํ•จํ•˜์ง€ ๋ชปํ•˜๋Š” ๊ฒฝ์šฐ

 

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

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

vector<int> solution(vector<string> gems) {
    // 1. ๋ณด์„ ์ข…๋ฅ˜ ๋ฐ ๊ฐœ์ˆ˜ ์„ธ๊ธฐ
    int N = gems.size();
    map<string, int> counts;
    for (const string& gem : gems)
        counts[gem]++;

    int gemKind = counts.size();
    counts.clear();

    // 2. ๋ชจ๋“  ์ข…๋ฅ˜์˜ ๋ณด์„์„ ํฌํ•จํ•˜๋Š” ๊ตฌ๊ฐ„์„ ์ฐพ์œผ๋ฉฐ ๊ฐฑ์‹ ํ•˜๊ธฐ
    int range = N;
    int start = 0, end = 0;
    vector<int> answer(2);

    while (true)
    {
        if (counts.size() != gemKind and end < N)
        {
            counts[gems[end++]]++;
            continue;
        }

        if (start > end or counts.size() != gemKind)
            break;

        counts[gems[start]]--;
        if (counts[gems[start]] == 0)
            counts.erase(gems[start]);
        start++;

		if (end - start < range)
		{
			range = end - start;
			answer[0] = start;
			answer[1] = end;
		}
    }

    return answer;
}

 

728x90
๋ฐ˜์‘ํ˜•