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.

链接:https://leetcode.com/problems/arranging-coins/#/description

3/25/2017

performance 4%, 87ms

错误:

1. 输入最大值

2. i的最大范围

 1 public class Solution {
 2     public int arrangeCoins(int n) {
 3         int m = n;
 4         for (int i = 0; i <= m; i++) {
 5             n -= i;
 6             if (n == 0) return i;
 7             else if (n < 0) return i - 1;
 8         }
 9         return -1;
10     }
11 }

别人的方法:

binary search

https://discuss.leetcode.com/topic/65593/java-clean-code-with-explanations-and-running-time-2-solutions

算式

https://discuss.leetcode.com/topic/65575/java-o-1-solution-math-problem/5

更多讨论

https://discuss.leetcode.com/category/567/arranging-coins

原文地址:https://www.cnblogs.com/panini/p/6619743.html