Algorithm Problem/Python

[python] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์Šคํƒ€ ์ˆ˜์—ด(์›”๊ฐ„ ์ฝ”๋“œ ์ฑŒ๋ฆฐ์ง€ ์‹œ์ฆŒ1)

deo2kim 2022. 2. 9. 22:06
๋ฐ˜์‘ํ˜•

๐Ÿค”๋ฌธ์ œ ํ•ด๊ฒฐ

1. ์ฃผ์–ด์ง„ ๋ฐฐ์—ด์˜ ์ˆซ์ž์˜ ๊ฐœ์ˆ˜๋ฅผ ์„ผ๋‹ค. -> Counter ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์ด์šฉ

2. ์ฃผ์–ด์ง„ ๋ฐฐ์—ด์—์„œ ๊บผ๋‚ธ ์ˆซ์ž์˜ ์ธ๋ฑ์Šค๋ฅผ ๊ตฌํ•œ๋‹ค.

3. ๊ตฌํ•œ ์ธ๋ฑ์Šค์˜ ์™ผ์ชฝ or ์˜ค๋ฅธ์ชฝ์˜ ์ˆซ์ž๋ฅผ ์ ์ ˆํ•˜๊ฒŒ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š”์ง€ ํŒ๋‹จํ•˜๊ณ  ์Šคํƒ€ ์ˆ˜์—ด์„ ๋งŒ๋“ ๋‹ค.

๐Ÿ’จ Counter ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ๋Œ€์‹  { 1: [0, 3, 6, 9], ... } ์ด๋Ÿฐ์‹์œผ๋กœ ์ธ๋ฑ์Šค๋ฅผ ๋„ฃ์–ด์ค˜์„œ ๊ธธ์ด์™€ ์ธ๋ฑ์Šค๋ฅผ ํ•œ๊บผ๋ฒˆ์— ์•Œ๊ธฐ ์‰ฝ๊ฒŒํ•˜๋Š” ๋ฐฉ๋ฒ•๋„ ๋ดค๋‹ค.

๐Ÿ’จ ์ค‘๊ฐ„ ์ค‘๊ฐ„ ๊ธธ์ด๊ฐ€ ์งง์€ ์• ๋“ค์„ ๋Š์–ด์ฃผ์ง€ ์•Š์œผ๋ฉด ์‹œ๊ฐ„์ดˆ๊ณผ ๋‚  ๊ฒƒ ๊ฐ™๋‹ค.

 

๐Ÿ’ป์†Œ์Šค ์ฝ”๋“œ

from collections import Counter


def solution(a):
    # ์ฃผ์–ด์ง„ ๋ฐฐ์—ด์˜ ์ˆซ์ž์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•œ๋‹ค.
    number_cnt = Counter(a)
    answer = 0

    # ๊ตฌํ•œ ์ˆซ์ž๋ฅผ ํ•˜๋‚˜ ์”ฉ ๊บผ๋‚ด์„œ
    for standard_number in number_cnt.keys():
        if number_cnt[standard_number] * 2 < answer:  # ์ด์ „์— ์™„์„ฑํ•œ ์Šคํƒ€์ˆ˜์—ด์˜ ๊ธธ์ด๋ณด๋‹ค ๊บผ๋‚ธ ์ˆซ์ž์˜ ๊ฐœ์ˆ˜๊ฐ€ ์ ์œผ๋ฉด
            continue                                    # ์Šคํƒ€์ˆ˜์—ด์„ ์™„์„ฑํ•ด๋„ ๊ธธ์ด๊ฐ€ ์งง์œผ๋ฏ€๋กœ ํŒจ์Šค

        number_index_list = []  # ์ฃผ์–ด์ง„ ๋ฐฐ์—ด์—์„œ ๊บผ๋‚ธ ์ˆซ์ž์˜ ์ธ๋ฑ์Šค๋ฅผ ๊ตฌํ•œ๋‹ค.
        for i in range(len(a)):
            if a[i] == standard_number:
                number_index_list.append(i)

        seq = []  # ์Šคํƒ€์ˆ˜์—ด์„ ์ €์žฅํ•  ๋ฐฐ์—ด
        before_selected_idx = -1  # ๊บผ๋‚ธ ์ˆซ์ž์˜ ์™ผ์ชฝ or ์˜ค๋ฅธ์ชฝ์˜ ์ˆซ์ž๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ ๊ฒน์ณ์„œ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ธฐ ์œ„ํ•ด์„œ
        cnt = 0  # ์Šคํƒ€์ˆ˜์—ด์˜ ๊ธธ์ด ์ €์žฅ
        for idx in number_index_list:
            if 0 <= idx - 1 != before_selected_idx and a[idx] != a[idx - 1]: # ๊ธฐ์ค€ ์ˆซ์ž์˜ ์™ผ์ชฝ ์ˆซ์ž ์‚ฌ์šฉ
                seq.append([a[idx - 1], a[idx]])
                before_selected_idx = idx - 1
                cnt += 1
            elif len(a) > idx + 1 != before_selected_idx and a[idx] != a[idx + 1]: # ๊ธฐ์ค€ ์ˆซ์ž์˜ ์˜ค๋ฅธ์ชฝ ์ˆซ์ž ์‚ฌ์šฉ
                seq.append([a[idx], a[idx + 1]])
                before_selected_idx = idx + 1
                cnt += 1

        else:
            answer = cnt * 2

    return answer

 

๐Ÿ“•๋ฌธ์ œ ํ™•์ธ

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

๋งํฌ: ์Šคํƒ€ ์ˆ˜์—ด

๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€์ˆ˜0