138.Arranging Coins
Posted chanaichao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了138.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.
您想要以楼梯形状形成总共n个硬币,其中每个第k行必须具有恰好k个硬币。
Given n, find the total number of full staircase rows that can be formed.
给定n,找到可以形成的完整楼梯行的总数。
n is a non-negative integer and fits within the range of a 32-bit signed integer.
n是一个非负整数,适合32位有符号整数的范围。
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.
解答:
方法一:时间复杂度O(n)
1 class Solution { 2 public int arrangeCoins(int n) { 3 if(n==0) return n; 4 int curr=1,remain=n-1; 5 while(remain>=curr+1){ 6 curr++; 7 remain-=curr; 8 } 9 return curr; 10 } 11 }
方法二:时间复杂度O(logn)
1 class Solution { 2 public int arrangeCoins(int n) { 3 if(n<=1) return n; 4 long low=1,high=n; 5 while(low<high){ 6 long mid=low+(high-low)/2; 7 if(mid*(mid+1)/2<=n) low=mid+1; 8 else high=mid; 9 } 10 return (int)low-1; 11 } 12 }
方法三:
1 class Solution { 2 public int arrangeCoins(int n) { 3 return (int)((-1+Math.sqrt(1+8*(long)n))/2); 4 } 5 }
详解:
方法一:暴力解法
curr:当前行数也是当前硬币个数
remain:剩余硬币数
从第1行开始遍历,用剩余硬币数减去行数,如果剩余的硬币无法满足下一行需要的硬币数,终止
方法二:二分搜索法
找到前k行之和刚好大于n,k-1即为解
方法三:等差数列性质
n = (1 + x) * x / 2,得 x = (-1 + sqrt(8 * n + 1)) / 2, 取整
以上是关于138.Arranging Coins的主要内容,如果未能解决你的问题,请参考以下文章