LeetCode 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.
问n个硬币最多能摆成多少级台阶,每级台阶的硬币数是以1为步长递增的。其实就是求1+2+…+k<=n的最大的k。当然最简单的方法是暴力枚举[1,n]之间的k。 O(lgn)的方法是二分搜索满足上述不等式的最大的k。代码如下: [cpp] class Solution { public: int arrangeCoins(int n) { long long l = 0, r = n; while (l <= r) { long long m = (l + r) / 2; long long sum = (1 + m)*m / 2; if (n < sum)r = m – 1; else l = m + 1; } return r; } }; [/cpp] 本代码提交AC,用时35MS。 参考:http://bookshadow.com/weblog/2016/10/30/leetcode-arranging-coins/ P.S.感觉二分搜索的代码边界条件很麻烦。。。]]>