Back-end/Algorithm

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ํ–„๋ฒ„๊ฑฐ ๋งŒ๋“ค๊ธฐ (java)

Nellie Kim 2023. 8. 18. 22:27
728x90

๐Ÿ’‍โ™€๏ธ  ๋ฌธ์ œ ์„ค๋ช…

ํ–„๋ฒ„๊ฑฐ ๊ฐ€๊ฒŒ์—์„œ ์ผ์„ ํ•˜๋Š” ์ƒ์ˆ˜๋Š” ํ–„๋ฒ„๊ฑฐ๋ฅผ ํฌ์žฅํ•˜๋Š” ์ผ์„ ํ•ฉ๋‹ˆ๋‹ค. ํ•จ๊ป˜ ์ผ์„ ํ•˜๋Š” ๋‹ค๋ฅธ ์ง์›๋“ค์ด ํ–„๋ฒ„๊ฑฐ์— ๋“ค์–ด๊ฐˆ ์žฌ๋ฃŒ๋ฅผ ์กฐ๋ฆฌํ•ด ์ฃผ๋ฉด ์กฐ๋ฆฌ๋œ ์ˆœ์„œ๋Œ€๋กœ ์ƒ์ˆ˜์˜ ์•ž์— ์•„๋ž˜์„œ๋ถ€ํ„ฐ ์œ„๋กœ ์Œ“์ด๊ฒŒ ๋˜๊ณ , ์ƒ์ˆ˜๋Š” ์ˆœ์„œ์— ๋งž๊ฒŒ ์Œ“์—ฌ์„œ ์™„์„ฑ๋œ ํ–„๋ฒ„๊ฑฐ๋ฅผ ๋”ฐ๋กœ ์˜ฎ๊ฒจ ํฌ์žฅ์„ ํ•˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค. ์ƒ์ˆ˜๊ฐ€ ์ผํ•˜๋Š” ๊ฐ€๊ฒŒ๋Š” ์ •ํ•ด์ง„ ์ˆœ์„œ(์•„๋ž˜์„œ๋ถ€ํ„ฐ, ๋นต – ์•ผ์ฑ„ – ๊ณ ๊ธฐ - ๋นต)๋กœ ์Œ“์ธ ํ–„๋ฒ„๊ฑฐ๋งŒ ํฌ์žฅ์„ ํ•ฉ๋‹ˆ๋‹ค. ์ƒ์ˆ˜๋Š” ์†์ด ๊ต‰์žฅํžˆ ๋น ๋ฅด๊ธฐ ๋•Œ๋ฌธ์— ์ƒ์ˆ˜๊ฐ€ ํฌ์žฅํ•˜๋Š” ๋™์•ˆ ์† ์žฌ๋ฃŒ๊ฐ€ ์ถ”๊ฐ€์ ์œผ๋กœ ๋“ค์–ด์˜ค๋Š” ์ผ์€ ์—†์œผ๋ฉฐ, ์žฌ๋ฃŒ์˜ ๋†’์ด๋Š” ๋ฌด์‹œํ•˜์—ฌ ์žฌ๋ฃŒ๊ฐ€ ๋†’์ด ์Œ“์—ฌ์„œ ์ผ์ด ํž˜๋“ค์–ด์ง€๋Š” ๊ฒฝ์šฐ๋Š” ์—†์Šต๋‹ˆ๋‹ค.

์˜ˆ๋ฅผ ๋“ค์–ด, ์ƒ์ˆ˜์˜ ์•ž์— ์Œ“์ด๋Š” ์žฌ๋ฃŒ์˜ ์ˆœ์„œ๊ฐ€ [์•ผ์ฑ„, ๋นต, ๋นต, ์•ผ์ฑ„, ๊ณ ๊ธฐ, ๋นต, ์•ผ์ฑ„, ๊ณ ๊ธฐ, ๋นต]์ผ ๋•Œ, ์ƒ์ˆ˜๋Š” ์—ฌ์„ฏ ๋ฒˆ์งธ ์žฌ๋ฃŒ๊ฐ€ ์Œ“์˜€์„ ๋•Œ, ์„ธ ๋ฒˆ์งธ ์žฌ๋ฃŒ๋ถ€ํ„ฐ ์—ฌ์„ฏ ๋ฒˆ์งธ ์žฌ๋ฃŒ๋ฅผ ์ด์šฉํ•˜์—ฌ ํ–„๋ฒ„๊ฑฐ๋ฅผ ํฌ์žฅํ•˜๊ณ , ์•„ํ™‰ ๋ฒˆ์งธ ์žฌ๋ฃŒ๊ฐ€ ์Œ“์˜€์„ ๋•Œ, ๋‘ ๋ฒˆ์งธ ์žฌ๋ฃŒ์™€ ์ผ๊ณฑ ๋ฒˆ์งธ ์žฌ๋ฃŒ๋ถ€ํ„ฐ ์•„ํ™‰ ๋ฒˆ์งธ ์žฌ๋ฃŒ๋ฅผ ์ด์šฉํ•˜์—ฌ ํ–„๋ฒ„๊ฑฐ๋ฅผ ํฌ์žฅํ•ฉ๋‹ˆ๋‹ค. ์ฆ‰, 2๊ฐœ์˜ ํ–„๋ฒ„๊ฑฐ๋ฅผ ํฌ์žฅํ•˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.

์ƒ์ˆ˜์—๊ฒŒ ์ „ํ•ด์ง€๋Š” ์žฌ๋ฃŒ์˜ ์ •๋ณด๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ์ •์ˆ˜ ๋ฐฐ์—ด ingredient๊ฐ€ ์ฃผ์–ด์กŒ์„ ๋•Œ, ์ƒ์ˆ˜๊ฐ€ ํฌ์žฅํ•˜๋Š” ํ–„๋ฒ„๊ฑฐ์˜ ๊ฐœ์ˆ˜๋ฅผ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•˜์‹œ์˜ค.


โŒ ์ œํ•œ์‚ฌํ•ญ

  • 1 ≤ ingredient์˜ ๊ธธ์ด ≤ 1,000,000
  • ingredient์˜ ์›์†Œ๋Š” 1, 2, 3 ์ค‘ ํ•˜๋‚˜์˜ ๊ฐ’์ด๋ฉฐ, ์ˆœ์„œ๋Œ€๋กœ ๋นต, ์•ผ์ฑ„, ๊ณ ๊ธฐ๋ฅผ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค.

 

 

๐Ÿ’ก  ์ž…์ถœ๋ ฅ ์˜ˆ

 

 

์ž…์ถœ๋ ฅ ์˜ˆ #1

  • ๋ฌธ์ œ ์˜ˆ์‹œ์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค.

 

์ž…์ถœ๋ ฅ ์˜ˆ #2

  • ์ƒ์ˆ˜๊ฐ€ ํฌ์žฅํ•  ์ˆ˜ ์žˆ๋Š” ํ–„๋ฒ„๊ฑฐ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.

 

๐Ÿ‘ฉ ๋‚ด ํ’€์ด

class Solution {
    public int solution(int[] ingredient) {
        int[] stack = new int[ingredient.length];
        int sp = 0;
        int answer = 0;
        for (int i : ingredient) {
            stack[sp++] = i;
            if (sp >= 4 && stack[sp - 1] == 1
                && stack[sp - 2] == 3
                && stack[sp - 3] == 2
                && stack[sp - 4] == 1) {
                sp -= 4;
                answer++;
            }
        }
        return answer;
    }
}