ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90

 

๐Ÿฅ 2020 ์นด์นด์˜ค ์ธํ„ด์‹ญ

 

๋ฌธ์ œ

 

thinking

์™„์ „ํƒ์ƒ‰์œผ๋กœ ํ’€๋ฉด ์‹œ๊ฐ„๋ณต์žก๋„ O(N²) ์—ฌ์„œ ์•ˆ๋จ. ->  ํˆฌํฌ์ธํ„ฐ  ๋กœ ํ’€์ž

1. ์‹คํŒจ์ฝ”๋“œ

์ฒ˜์Œ์— ๋ฆฌ์ŠคํŠธ ์Šฌ๋ผ์ด์‹ฑ๊ณผ set์„ ์ด์šฉํ•ด ํ’€์—ˆ๋Š”๋ฐ ํšจ์œจ์„ฑ์ด ๋˜ฅ๋ง์ด์—ˆ๋‹ค.... ์™œ???????????????? ํˆฌํฌ์ธํ„ฐ๋กœ ํ’€์—ˆ๋Š”๋ฐ ๐Ÿ˜ฒ

def solution(gems):
    N = len(gems)
    answer = [0, N-1]
    kind = set(gems)
    s,e = 0,0  # ํˆฌํฌ์ธํ„ฐ
    while 0<=s<N and 0<=e<N:
        if set(gems[s:e+1]) == kind:  # ๋ชจ๋“  ์ข…๋ฅ˜ ๋‹ค ๊ฐ–๊ณ  ์žˆ์œผ๋ฉด start point ์ฆ๊ฐ€์‹œํ‚ค๋ฉด์„œ ์ตœ์†Œ๊ตฌ๊ฐ„ ๊ตฌํ•˜๊ธฐ
            if (e-s+1) < (answer[1]-answer[0]+1):
                answer = [s,e]
            s += 1
        else:  # ์ข…๋ฅ˜ ๋ถ€์กฑํ•˜๋ฉด end point ์ฆ๊ฐ€์‹œํ‚ค๊ธฐ
            e += 1
    answer[0] += 1
    answer[1] += 1
    return answer

์™œ๋ƒํ•˜๋ฉด ๋ฆฌ์ŠคํŠธ ์Šฌ๋ผ์ด์‹ฑ์œผ๋กœ ํ’€์—ˆ๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ์Šฌ๋ผ์ด์‹ฑ์€ ๊ฐ์ฒด k๊ฐœ๋ฅผ ์กฐํšŒํ•ด์•ผํ•˜๋ฏ€๋กœ ์‹œ๊ฐ„๋ณต์žก๋„๊ฐ€ O(k)์ด๋‹ค. ๊ฑฐ์˜ ๋ญ ์™„ํƒํ•˜๋Š” ์ˆ˜์ค€ ;;; ๊ทธ๋ž˜์„œ ๊ฒฐ๋ก ์€ ์Šฌ๋ผ์ด์‹ฑ์„ ๋ฒ„๋ ค๋ผ !!!!!!!!!

 

2. ๋งž์€์ฝ”๋“œ

์นด์นด์˜ค ํ…Œํฌ ๋ธ”๋กœ๊ทธ ํ•ด์„ค์„ ๋ณด๋‹ˆ  ๋”•์…”๋„ˆ๋ฆฌ ๋กœ ํ’€๋ผ๊ธธ๋ž˜ ์žฌ๋„์ „ํ•ด๋ดค๋‹ค

์นด์นด์˜ค ๊ณต์‹ ํ•ด์„ค

 

์ฝ”๋“œ

def solution(gems):
    N = len(gems)
    answer = [0, N-1]
    kind = len(set(gems))  # ๋ณด์„์ข…๋ฅ˜
    dic = {gems[0]:1,}  # ์ข…๋ฅ˜ ์ฒดํฌํ•  ๋”•์…”๋„ˆ๋ฆฌ
    s,e = 0,0  # ํˆฌํฌ์ธํ„ฐ
    while s<N and e<N:
        if len(dic) < kind:  # ์ข…๋ฅ˜ ๋ถ€์กฑํ•˜๋ฉด end point ์ฆ๊ฐ€ & dic ๊ฐœ์ˆ˜ ์ฆ๊ฐ€
            e += 1
            if e == N:
                break
            dic[gems[e]] = dic.get(gems[e], 0) + 1
            
        else:  # ์ข…๋ฅ˜ ๊ฐ™์œผ๋ฉด ans ๋น„๊ต ํ›„ ๋‹ต ๊ฐฑ์‹ ํ•˜๊ณ , start point ์ฆ๊ฐ€ & dic ๊ฐœ์ˆ˜ ๋‹ค์šด
            if (e-s+1) < (answer[1]-answer[0]+1):
                answer = [s,e]
            if dic[gems[s]] == 1:
                del dic[gems[s]]
            else:
                dic[gems[s]] -= 1
            s += 1

    answer[0] += 1
    answer[1] += 1
    return answer

๋Œ“๊ธ€