码迷,mamicode.com
首页 > 其他好文 > 详细

138.Arranging Coins

时间:2018-09-05 21:56:55      阅读:262      评论:0      收藏:0      [点我收藏+]

标签:where   复杂度   turn   题目   ever   coin   bec   fit   pre   

题目:

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

标签:where   复杂度   turn   题目   ever   coin   bec   fit   pre   

原文地址:https://www.cnblogs.com/chanaichao/p/9592469.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!