leetcode-441. Arranging Coins

来源:互联网 发布:电脑远程软件 编辑:程序博客网 时间:2024/05/16 19:12

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。

博客链接:mcf171的博客

——————————————————————————————

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.
这个题目其实还蛮简单的,不过也犯了一个错误,就是n*2会溢出,所以先转换为long再处理。Your runtime beats 78.99% of java submissions.

public class Solution {    public int arrangeCoins(int n) {        long val = n;        double value = Math.sqrt(val*2);        int high = (int)(Math.ceil(value));        for(int i = high; i >= 1; i --){            if(i*(i+1)<=n*2) {high = i;break;}        }        return high;    }}





0 0
原创粉丝点击