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

    1+2+3...+k <= n 求k的最大值

    C++(22ms):
     1 class Solution {
     2 public:
     3     int arrangeCoins(int n) {
     4         int left = 0 ;
     5         int right = n ;
     6         while(left <= right){
     7             int mid = left + (right - left) / 2 ;
     8             if (0.5 * (1+mid) * mid <= n)
     9                 left = mid + 1;
    10             else
    11                 right = mid - 1;
    12         }
    13         return left - 1 ;
    14     }
    15 };
    
    
    
     

    java(61ms):

    1 class Solution {
    2     public int arrangeCoins(int n) {
    3         return (int)((-1 + Math.sqrt(1 + 8 * (long)n)) / 2);
    4     }
    5 }
     
  • 相关阅读:
    Scala: 包对象
    云服务使用技巧
    leetcode上一些常见的链表问题
    数据挖掘的价值
    leetcode上的一些分治算法
    双指针的应用
    KNN算法
    线性回归
    leetcode上的一些单链表
    leetcode上的一些栈、队列问题
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/7880022.html
Copyright © 2011-2022 走看看