[Programmers] Lv2. ์ˆซ์ž์˜ ํ‘œํ˜„ | C++

2023. 6. 12. 20:27ใ†Coding Test/Programmers

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

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

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

programmers.co.kr

 

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

 

  1. for๋ฌธ์„ ํ†ตํ•ด ์ž์—ฐ์ˆ˜ 1๋ถ€ํ„ฐ ์ฐจ๋ก€๋Œ€๋กœ ํ•ฉ๊ณ„์— ๋”ํ•˜๊ณ , Queue์—๋„ ์›์†Œ๋ฅผ ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค.
  2. ๋งŒ์•ฝ ํ•ฉ๊ณ„๊ฐ€ n๊ณผ ๊ฐ™๋‹ค๋ฉด answer + 1๋ฅผ ํ•ด์ฃผ๊ณ , n < ํ•ฉ๊ณ„๊ฐ€ ๋˜๋Š” ์ƒํ™ฉ์ด๋ผ๋ฉด Queue์—์„œ ํ•˜๋‚˜์”ฉ pop ํ•˜์—ฌ ํ•ฉ๊ณ„์—์„œ ๋บ๋‹ˆ๋‹ค.
  3. Queue์˜ ์›์†Œ๋ฅผ popํ•˜์—ฌ ๋บ€ ํ•ฉ๊ณ„๊ฐ€ n๊ณผ ๊ฐ™๋‹ค๋ฉด answer + 1์„ ํ•ด ์ฃผ๊ณ , ์•„๋‹ˆ๋ผ๋ฉด ํ๊ฐ€ ๋น„๊ฑฐ๋‚˜, ํ•ฉ๊ณ„ < n์ด ๋˜๋Š” ์ƒํ™ฉ๊นŒ์ง€ ์ง„ํ–‰ํ•ด์ค๋‹ˆ๋‹ค.

 

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

#include <string>
#include <queue>
using namespace std;

int solution(int n) {
    queue<int> myQueue;
    int answer = 0;
    int sum = 0;

    for (int i = 1; i <= n; i++) {
        sum += i;
        myQueue.push(i);

        if (sum == n)
            answer++;
        else if (n < sum) {
            while (!myQueue.empty()) {
                int num = myQueue.front();
                myQueue.pop();
                sum -= num;

                if (sum == n)
                    answer++;
                else if (sum < n)
                    break;
            }
        }
    }

    return answer;
}

 

 

 

 

728x90
๋ฐ˜์‘ํ˜•