1. 程式人生 > >LeetCode 441. Arranging Coins

LeetCode 441. Arranging Coins

form following n-n win ems 標簽 example lan 3rd

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.


題目標簽:Math

  題目給了我們 coins 的總數, n, 讓我們找出可以組成幾行,返回 行數。

  首先來看一下規律:

1 x 1 * 2 / 2 = 1

2 x x 2 * 3 / 2 = 3

3 x x x 3 * 4 / 2 = 6

4 x x x x 4 * 5 / 2 = 10

5 x x x x x 5 * 6 / 2 = 15

  可以利用公式 x * (x + 1) / 2 來算出, 某一行累積的總 coins 數量。

  然後我們要找到的行數的總 coins 數量 一定是 小於等於 n 的。所以可以從 x * (x + 1) / 2 <= n 求出 x。

Java Solution:

Runtime beats 66.14%

完成日期:02/08/2018

關鍵詞:math

關鍵點:利用公式 x * (x + 1) / 2 和 quadratic equation

1 class Solution 
2 {
3     public int arrangeCoins(int n) 
4     {
5         return (int)((-1 + Math.sqrt(1 + 8.0 * n)) / 2);
6     }
7 }

參考資料:https://leetcode.com/problems/arranging-coins/discuss/92298/Java-O(1)-Solution-Math-Problem

LeetCode 題目列表 - LeetCode Questions List

題目來源:https://leetcode.com/

LeetCode 441. Arranging Coins