๐ŸŽฒ[์•Œ๊ณ ๋ฆฌ์ฆ˜] Lower bound / Upper bound

์ด๊ฐ•์šฑยท2022๋…„ 10์›” 16์ผ
0

๐ŸŽฒ ์•Œ๊ณ ๋ฆฌ์ฆ˜

๋ชฉ๋ก ๋ณด๊ธฐ
3/5

Lower bound

  • ์ •๋ ฌ๋œ ๋ฐฐ์—ด์—์„œ ์ฐพ๊ณ ์ž ํ•˜๋Š” ๊ฐ’(key) ์ด์ƒ์˜ ๊ฐ’์ด ์ฒ˜์Œ ๋‚˜ํƒ€๋‚˜๋Š” ์œ„์น˜.
# Lower bound
# nums[k-1] < key ์ด๊ณ , key <= nums[k]์ธ k๋ฅผ ์ฐพ๋Š”๋‹ค.

def lower_bound(nums, key):
    
    left, right = 0, len(nums)-1
    
    while left < right:  #left์™€ right๊ฐ€ ๋งŒ๋‚˜๋Š” ์ง€์ ์ด key๊ฐ’ ์ด์ƒ์ด ์ฒ˜์Œ ๋‚˜์˜ค๋Š” ์œ„์น˜
        mid = (left + right) // 2		# ๋‚˜๋ž€ํžˆ ๋‘๊ฐœ๊ฐ€ ๋‚จ์•˜์„ ๋•Œ mid๊ฐ€ ์™ผ์ชฝ์ด๋ฏ€๋กœ,
        								# ์˜ค๋ฅธ์ชฝ(right)์„ mid์™€ ๊ฐ™๊ฒŒํ•ด์ฃผ์–ด์•ผ ๋ฌดํ•œ๋ฃจํ”„์— ๋น ์ง€์ง€ ์•Š๋Š”๋‹ค.
        
        if key <= nums[mid]:
         	right = mid		# ์ด ๊ฐฑ์‹ ์„ ํ†ตํ•ด, right์— ํ•ด๋‹นํ•˜๋Š” ๊ฐ’์€ key ๋ณด๋‹ค '์ด์ƒ'์ž„์„ ๋ณด์žฅํ•œ๋‹ค.
        else:
           left = mid + 1

    
    return right			# ๋ณด์žฅ๋œ ๊ฐ’์— ๋Œ€ํ•œ ์ธ๋ฑ์Šค๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

Upper bound

  • ์ •๋ ฌ๋œ ๋ฐฐ์—ด์—์„œ ์ฐพ๊ณ ์ž ํ•˜๋Š” ๊ฐ’(key)์„ ์ดˆ๊ณผํ•˜๋Š” ๊ฐ’์ด ์ฒ˜์Œ ๋‚˜ํƒ€๋‚˜๋Š” ์œ„์น˜.

# Upper bound
# nums[k-1] <= key ์ด๊ณ , key < nums[k]์„ ๋งŒ์กฑํ•˜๋Š” ์ตœ์†Œ k๋ฅผ ์ฐพ๋Š”๋‹ค.

def upper_bound(nums, key):

    left, right = 0, len(nums)-1

    while left < right:  #left์™€ right๊ฐ€ ๋งŒ๋‚˜๋Š” ์ง€์ ์ด key๊ฐ’์„ ์ดˆ๊ณผํ•˜๋Š” ๊ฐ’์ด ์ฒ˜์Œ ๋‚˜์˜ค๋Š” ์œ„์น˜
        mid = (left + right) // 2		# ๋‚˜๋ž€ํžˆ ๋‘๊ฐœ๊ฐ€ ๋‚จ์•˜์„ ๋•Œ mid๊ฐ€ ์™ผ์ชฝ์ด๋ฏ€๋กœ,
        								# ์˜ค๋ฅธ์ชฝ(right)์„ mid์™€ ๊ฐ™๊ฒŒํ•ด์ฃผ์–ด์•ผ ๋ฌดํ•œ๋ฃจํ”„์— ๋น ์ง€์ง€ ์•Š๋Š”๋‹ค.

		if key < nums[mid]:		
        	right = mid		# ์ด ๊ฐฑ์‹ ์„ ํ†ตํ•ด, right์— ํ•ด๋‹นํ•˜๋Š” ๊ฐ’์€ key์„ '์ดˆ๊ณผ'ํ•œ ๊ฐ’์ž„์„ ๋ณด์žฅํ•œ๋‹ค.
        else:
            left = mid + 1 

    return right			# ๋ณด์žฅ๋œ ๊ฐ’์— ๋Œ€ํ•œ ์ธ๋ฑ์Šค๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
profile
I think I think too much.

0๊ฐœ์˜ ๋Œ“๊ธ€