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.
count is the # of level, sum is the accumulated coins
1 public class Solution { 2 public int arrangeCoins(int n) { 3 long sum = 0; 4 int count = 0; 5 while (true) { 6 sum = sum + count; 7 if (n < sum) break; 8 count++; 9 } 10 return count - 1; 11 } 12 }
Better Solution:
Binary Search, 因为怕溢出,所以(1+m)m/2表示成了line6那种样子.
用m去估计最后返回的row
0.5*m+0.5*m*m > n 表示前m row的和大于了n, 如果这个m作为返回值的话肯定是取大了,所以r减小,如果
0.5*m+0.5*m*m <= n 表示m是合适的,或者偏小了,这个时候增大l,如果l>r,r就一定落在m处
1 public class Solution { 2 public int arrangeCoins(int n) { 3 int l=1, r=n; 4 while (l <= r) { 5 int m = l + (r-l)/2; 6 if (0.5*m+0.5*m*m > n) { 7 r = m - 1; 8 } 9 else l = m + 1; 10 } 11 return r; 12 } 13 }