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/

  • 相关阅读:
    【jQuery 分页】jQuery分页功能的实现
    【jQuery 使用】 利用jQuery.prop("outerHTML")获取包含自身在内的HTML元素的HTML代码
    Openfire 是怎么存离线消息
    openfire过滤脏话插件,控制消息是否发送
    openfire升级指南
    openfire教程网
    redis web 客户端工具 redis-admin
    敏捷开发Nutz
    openfire消息通知推送
    一步步教你实现跨游览器的颜色选择器
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/8434803.html
Copyright © 2011-2022 走看看