【LeeCode】441. 排列硬币

时间:2021-10-10 01:25:12

【题目描述】

你总共有 n 枚硬币,并计划将它们按阶梯状排列。对于一个由 k 行组成的阶梯,其第 i 行必须正好有 i 枚硬币。阶梯的最后一行 可能 是不完整的。

给你一个数字 n ,计算并返回可形成 完整阶梯行 的总行数。

https://leetcode.cn/problems/arranging-coins/


【示例】

【LeeCode】441. 排列硬币

【LeeCode】441. 排列硬币

【代码】二分法


【代码】leecode

import java.util.*;
// 2023-4-6

class Solution {
    public int arrangeCoins(int n) {
        int res = 0;
        while (n - res > 0)
            n -= ++res;
        return res;
    }
}

public class Main {
    public static void main(String[] args) {
        new Solution().arrangeCoins(5); // 输出:2
        new Solution().arrangeCoins(8); // 输出:3
        new Solution().arrangeCoins(3); // 输出:2
    }
}

【代码】admin

题外话: 这个题,我竟然基于debug做出来了,第一眼看完全想不到思路

import java.util.*;
// 2023-4-6

class Solution {
    public int arrangeCoins(int n) {
        // 如果是1, 则返回1即可
        if (n == 1) return 1;
        int index = 0;
        for (int i = 1; i <= n ; i++) {
            n -= i;
            if (n < 0) {
                return index - 1;
            }else if (n == 0){
                // 如果刚好为0, 则也要加1
                index++;
                return index;
            }
            index++;
        }
        return index;
    }
}
public class Main {
    public static void main(String[] args) {
        new Solution().arrangeCoins(5); // 输出:2
        new Solution().arrangeCoins(8); // 输出:3
        new Solution().arrangeCoins(3); // 输出:2
    }
}