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

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

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

programmers.co.kr

 

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

 

๋ฌธ์ œ์—์„œ ์Šคํƒ(Stack) ์“ฐ๋ผ๊ณ  ๋Œ€๋†“๊ณ  ์ œ์‹œํ•ด์ค˜์„œ, ์Šคํƒ ์ผ์Šต๋‹ˆ๋‹ค. ๋‹ค๋งŒ, order ๊ธธ์ด๊ฐ€ ๋ฐฑ๋งŒ ๊ฐœ๋ผ ์‹œ๊ฐ„ ์ดˆ๊ณผ๊ฐ€ ๋‚ ๊นŒ ๊ฑฑ์ •ํ–ˆ๋Š”๋ฐ ์•ˆ ๋‚˜๋”๋ผ๊ตฌ์š”. ์•„๋ฌด๋ž˜๋„ ์‹ค์„ ์ˆ˜ ์—†๋Š” ๊ฒฝ์šฐ๊ฐ€ ์ƒ๊ธฐ๊ธฐ์— ๋ฐฑ๋งŒ ๊ฐœ๋ฅผ ๋‹ค ๋ณด์ง€ ์•Š์•„์„œ ๊ทธ๋Ÿฐ๊ฐ€ ๋ด…๋‹ˆ๋‹ค.

์ €๋Š” ๋‹ค์Œ ์ˆœ์„œ๋ฅผ ํ†ตํ•ด ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•˜์˜€์Šต๋‹ˆ๋‹ค.

 

  • ํ˜„์žฌ ํƒ๋ฐฐ ์ƒ์ž ๋ฒˆํ˜ธ == order[i]๋ผ๋ฉด, answer + 1์„ ํ•ด์ค๋‹ˆ๋‹ค.
  • ํ˜„์žฌ ํƒ๋ฐฐ ์ƒ์ž ๋ฒˆํ˜ธ < order[i]๋ผ๋ฉด, order[i] - 1๊นŒ์ง€ ์Šคํƒ์— ๋„ฃ์–ด์ฃผ๊ณ  answer + 1์„ ํ•ด์ค๋‹ˆ๋‹ค. ๊ทธ ํ›„, ํ˜„์žฌ ํƒ๋ฐฐ ์ƒ์ž ๋ฒˆํ˜ธ = order[i] + 1๋กœ ๊ฐฑ์‹ ์‹œ์ผœ ์ค๋‹ˆ๋‹ค.
  • ํ˜„์žฌ ํƒ๋ฐฐ ์ƒ์ž ๋ฒˆํ˜ธ > order[i]๋ผ๋ฉด, ์Šคํƒ์˜ top๊ณผ order[i]์™€ ๋น„๊ตํ•ฉ๋‹ˆ๋‹ค.
    • ๊ฐ™๋‹ค๋ฉด answer + 1์„ ํ•ด์ฃผ๊ณ , pop์„ ํ•ฉ๋‹ˆ๋‹ค.
    • ์•„๋‹ˆ๋ผ๋ฉด ๋” ์ด์ƒ ์‹ค์„ ์ˆ˜ ์žˆ๋Š” ํƒ๋ฐฐ๊ฐ€ ์—†์œผ๋ฏ€๋กœ answer์„ ๋ฆฌํ„ดํ•ฉ๋‹ˆ๋‹ค.
  • ํ˜„์žฌ ํƒ๋ฐฐ ์ƒ์ž ๋ฒˆํ˜ธ๊ฐ€ ๋งˆ์ง€๋ง‰ ํƒ๋ฐฐ ์ƒ์ž ๋ฒˆํ˜ธ(order.size())๋ฅผ ๋„˜์–ด๊ฐ„๋‹ค๋ฉด, ์Šคํƒ์— ๋ชจ๋‘ ์Œ“์ธ ์ƒํƒœ์ด๋ฏ€๋กœ answer์— ์Šคํƒ ํฌ๊ธฐ๋งŒํผ ๋”ํ•˜๊ณ  ๋ฆฌํ„ดํ•ฉ๋‹ˆ๋‹ค.

 

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

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

int solution(vector<int> order) {
	int answer = 0;
	int deliveryBox = 1;
	stack<int> subContainer;

	for (const auto requiredOrder : order) {
		if (order.size() < deliveryBox) {
			answer += subContainer.size();
			break;
		}

		if (deliveryBox == requiredOrder) {
			deliveryBox++;
			answer++;
			continue;
		}

		if (deliveryBox < requiredOrder) {
			while (deliveryBox < requiredOrder) subContainer.emplace(deliveryBox++);
			answer++;
			deliveryBox++;
			continue;
		}

		if (deliveryBox > requiredOrder and !subContainer.empty()) {
			if (subContainer.top() == requiredOrder) {
				answer++;
				subContainer.pop();
				continue;
			}
			break;
		}
	}

	return answer;
}

 

 

 

728x90
๋ฐ˜์‘ํ˜•