leetcode:Binary Search 441. Arranging Coins

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 1:

n = 5

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

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

Example 2:

n = 8

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

Because the 4th row is incomplete, we return 3.



class Solution:
	def arrangeCoins(self, n):
		low = 0
		high = n
		while low<=high:
			mid = (low+high)//2
			sum_seq = lambda x:(1+x)*x//2
			if n<sum_seq(mid):
				high = mid - 1
			elif n>=sum_seq(mid+1): 
				low = mid + 1
			else:
				return mid

猜你喜欢

转载自blog.csdn.net/w16337231/article/details/80289920