๊ตฌ๋ช…๋ณดํŠธ - ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

๋ฌธ์ œ

๊ตฌ๋ช…๋ณดํŠธ

ํ•ด์„ค

  • ์ถœ์ œ์˜๋„๊ฐ€ ํˆฌํฌ์ธํ„ฐ์ธ๋“ฏ ํ•ด์„œ ํˆฌํฌ์ธํ„ฐ๋กœ ํ•ด๊ฒฐํ–ˆ๋‹ค.
  • ๊ธฐ๋ณธ์ ์œผ๋กœ ๊ตฌํ•˜๋Š” ๊ตฌ๋ช…๋ณดํŠธ์˜ ์ƒํ™ฉ์— ํฌ์ปค์Šค๋ฅผ ๋งž์ถ”๋Š”๊ฒŒ ํฌ์ธํŠธ๋‹ค.
    • ๊ตฌ๋ช…๋ณดํŠธ๋Š” 1๋ช… ํƒ€๊ฑฐ๋‚˜ 2๋ช… ํƒ€๋Š” ๋‘๊ฐ€์ง€ ์ผ€์ด์Šค๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๋‹ค.
    • ์ •๋ ฌ๋˜์–ด ์žˆ๋‹ค๋ฉด ๋ชธ๋ฌด๊ฒŒ๊ฐ€ ๊ฐ€์žฅ ์ž‘์€ ์‚ฌ๋žŒ๊ณผ ๊ฐ€์žฅ ํฐ ์‚ฌ๋žŒ์˜ ํ•ฉ์„ ๊ธฐ์ค€์œผ๋กœ ์ƒ๊ฐํ•˜๋Š”๊ฒŒ ํ•ฉ๋ฆฌ์ ์ด๋‹ค.
    • ์—ฌ๊ธฐ์„œ ๋‘ ์‚ฌ๋žŒ์˜ ํ•ฉ์ด limit๋ณด๋‹ค ํฌ๋‹ค๋ฉด, ๋ชธ๋ฌด๊ฒŒ๊ฐ€ ๊ฐ€์žฅ ํฐ ์‚ฌ๋žŒ๋ถ€ํ„ฐ ํ˜ผ์ž ๊ตฌ๋ช…๋ณดํŠธ๋กœ ํƒœ์›Œ ๋ณด๋‚ด๋ฉด ๋œ๋‹ค.
    • ๋ฐ˜๋ฉด์— ๋‘ ์‚ฌ๋žŒ์˜ ํ•ฉ์ด limit๋ณด๋‹ค ์ž‘์€ ์ƒํ™ฉ์ด ๋‚˜ํƒ€๋‚œ๋‹ค๋ฉด, ๊ทธ๋•Œ ๋น„๋กœ์†Œ 2๋ช…์„ ๊ตฌ๋ช…๋ณดํŠธ์— ํƒœ์›Œ์„œ ๋ณด๋‚ผ ์ˆ˜ ์žˆ๋‹ค.
    • ์กฐ๊ฑด์„ ์ž”๋œฉ ๋‹ฌ์•„์„œ if-else๋ฌธ์„ ๋งŒ๋“ค๋‹ค๊ฐ€ ๊ฝค ๊ณ ๋ฏผํ–ˆ๋Š”๋ฐ, ๊ทธ๊ฑฐ๋ณด๋‹จ ๋ฉ”์ธ-์˜ˆ์™ธ๋ฅผ ํ™œ์šฉํ•œ if๋ฌธ์œผ๋กœ ์ ‘๊ทผํ•˜๋Š”๊ฒŒ ๋” ๊น”๋”ํ•˜๋‹ค.(๋ฌด์—‡๋ณด๋‹ค ์‹œ๊ฐ„๋„ ์˜ค๋ž˜๊ฑธ๋ฆฌ๊ณ  if ์กฐ๊ฑด์„ ์ •ํ™•ํ•˜๊ฒŒ ๋งŒ๋“œ๋Š”๊ฒƒ๋„ ๊ต‰์žฅํžˆ ๊นŒ๋‹ค๋กญ๋‹ค.)

1. ์ฒ˜์Œ ํ’€์ด

def solution(people, limit):
    people = sorted(people) 
    num = len(people)
    left, right = 0, num - 1
    cnt = 0 
    while left <= right: 
    # ๊ตฌ๋ช…๋ณดํŠธ ๊ฐฏ์ˆ˜๋งŒ์„ ๊ตฌํ•˜๊ธฐ ๋•Œ๋ฌธ์— ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋Š” ํ†ต๊ณผํ–ˆ์ง€๋งŒ ๋…ผ๋ฆฌ์ ์œผ๋กœ๋Š” ๋งž์ง€ ์•Š๋‹ค.
        if people[left] + people[right] > limit:
            right -= 1
            cnt += 1
        else:
            left += 1
            right -= 1
            cnt += 1
    return cnt 

2. ๋ฆฌํŒฉํ† ๋งํ•œ ํ’€์ด

def solution(people, limit):
    people = sorted(people) 
    num = len(people)
    left, right = 0, num - 1
    cnt = 0 
    while left < right: 
        # ์กฐ๊ฑด๋ฌธ์ด ํ›จ์”ฌ ๋‹จ์ˆœํ•ด์กŒ๋‹ค.
        if people[left] + people[right] <= limit:
            left += 1
        cnt += 1
        right -= 1
    if left == right: # ํ˜ผ์ž ๋‚จ์•˜์„ ๋•Œ, ์ด๋ ‡๊ฒŒ ๋”ฐ๋กœ ์ฒ˜๋ฆฌํ•ด์ค˜์•ผ ๋…ผ๋ฆฌ์ ์œผ๋กœ ์ •ํ™•ํ•˜๋‹ค.
        cnt += 1
    return cnt