博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode: Arranging Coins
阅读量:7077 次
发布时间:2019-06-28

本文共 1333 字,大约阅读时间需要 4 分钟。

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 = 5The coins can form the following rows:¤¤ ¤¤ ¤Because the 3rd row is incomplete, we return 2.Example 2:n = 8The coins can form the following rows:¤¤ ¤¤ ¤ ¤¤ ¤Because the 4th row is incomplete, we return 3.

count is the # of level, sum is the accumulated coins

1 public class Solution { 2     public int arrangeCoins(int n) { 3         long sum = 0; 4         int count = 0; 5         while (true) { 6             sum = sum + count; 7             if (n < sum) break; 8             count++; 9         }10         return count - 1;11     }12 }

 Better Solution:

Binary Search, 因为怕溢出,所以(1+m)m/2表示成了line6那种样子. 

 用m去估计最后返回的row

0.5*m+0.5*m*m > n 表示前m row的和大于了n, 如果这个m作为返回值的话肯定是取大了,所以r减小,如果
0.5*m+0.5*m*m <= n 表示m是合适的,或者偏小了,这个时候增大l,如果l>r,r就一定落在m处
1 public class Solution { 2     public int arrangeCoins(int n) { 3         int l=1, r=n; 4         while (l <= r) { 5             int m = l + (r-l)/2; 6             if (0.5*m+0.5*m*m > n) { 7                 r = m - 1;  8             } 9             else l = m + 1;10         }11         return r;12     }13 }

 

转载地址:http://tyvml.baihongyu.com/

你可能感兴趣的文章
Visual Studio 2017 15.9预览版3支持ARM64 for UWP
查看>>
LLVM3.8停止了旧Windows版本,取消Autoconf,改进Clang
查看>>
HTTP将死?又拍云布局HTTPS 护航网页安全加速
查看>>
Microsoft 365及应用开发的未来:微软BUILD 2018大会第二天主题演讲
查看>>
白话中台战略:中台是个什么鬼?
查看>>
Java值类型设计进展
查看>>
《Spark大数据分析》一书的书评和采访
查看>>
The Agile Mind-Set作者访谈
查看>>
Mads Torgersen介绍C# 7及后续版本新特性
查看>>
高通与华为短暂和解,理智看待国内5G现状
查看>>
Gartner调查:AI将成为企业颠覆的重要力量
查看>>
爱立信电信软件的持续交付
查看>>
微软必应从.NET Core 2.1获得了性能提升
查看>>
DevOps实战:Graphite监控上手指南
查看>>
SSPL的MongoDB再被抛弃,GUN Health也合流PostgreSQL
查看>>
知乎pure render专栏创办人@流形:选择React这条路,很庆幸
查看>>
修复.NET的HttpClient
查看>>
调查:Android的领先地位稳固
查看>>
在Maven项目中使用JUnit进行单元测试
查看>>
Docker发布应用程序指南
查看>>