zoukankan      html  css  js  c++  java
  • LeetCode 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.
    

    题目标签: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/

  • 相关阅读:
    MVC中单用户登录
    用CheckBox做删除时请不要使用@Html.CheckBoxFor
    MVC3"不允许启动新事务,因为有其他线程正在该会话中运行"错误解决方法
    下拉菜单DropDwon实现方法
    MVC3中Ajax.ActionLink用法
    删除时显示确认对话框
    民航指令学习(一)
    CentOS常用命令
    CentOS手动分区步骤
    CentOS下安装JDK和Tomcat
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/8434803.html
Copyright © 2011-2022 走看看