【LeetCode】441. Arranging Coins python 解题思路

Description

You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins.

Given n, find the total number of full staircase rows that can be formed.

n is a non-negative integer and fits within the range of a 32-bit signed integer.

Example

n = 5

The coins can form the following rows:
¤
¤ ¤
¤ ¤

Because the 3rd row is incomplete, we return 2.

Analysis

For this problem, I want to use binary search to solve this problem, so we need tow pointers: left and right. The target is that we need find the min value m to achive (1+m)*m/2 < n. let me show my code:

class Solution(object):
    def arrangeCoins(self,n):
        """
        type: n int
        rtype: int
        """
        left, right =  0, n+1
        while left < right:
            mid = left + (right - left)/2
            if (1 + mid) * mid / 2 <= n:
                mid = left + 1
            else: mid = right
        return left - 1
            

 

你可能感兴趣的:(【LeetCode】441. Arranging Coins python 解题思路)