2023年7月10日 星期一

7/9 每日一題(等比級數, 二分搜索法)

You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the ith row has exactly i coins. The last row of the staircase may be incomplete.

Given the integer n, return the number of complete rows of the staircase you will build.

 

Example 1:

Input: n = 5
Output: 2
Explanation: Because the 3rd row is incomplete, we return 2.

Example 2:

Input: n = 8
Output: 3
Explanation: Because the 4th row is incomplete, we return 3.

 

Constraints:

  • 1 <= n <= 231 - 1


class Solution:
    def arrangeCoins(self, n: int) -> int:
        floor=0
        floor_sum = 0
        while floor_sum <= n:
            floor +=1
            floor_sum +=floor            

        if floor_sum==n:
            return floor
        else:
            return floor-1

------------------------參考解答 二分法
def f(n):
    left,right=0,n
    while left <= right:
        mid=left+(right-left)//2
        total=((mid+1)*mid)//2 #計算中間行所需的總硬幣
        #首相是1,公差是1一直加到mid項
        #例如mid=3 , 3*4//2=6 表示地3行需要6個硬幣
        if total == n:
            return print(f'找到mid={mid},total={total}')
        elif total > n:
            print(f'left={left}')
            print(f'right={right}')            
            print(f'mid={mid}')
            print(f'total={total}')
            right=mid -1
            print(f'mid超出n,right左移={right}')
            print()
        else:
            print(f'left={left}')
            print(f'right={right}')            
            print(f'mid={mid}')
            print(f'total={total}')
            left = mid+1
            print(f'mid小於n,left右移={left}')
            print()
    return print(f'返回最大完整數={right}')
f(5)



---------------------
left=0 right=10 mid=5 total=15 mid超出n,right左移=5 left=0 right=5 mid=2 total=3 mid小於n,left右移=3 找到mid=4,total=10













































標籤:

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁