跳转至

441.Arranging Coins

Tags: Easy Binary Search

Links: https://leetcode.com/problems/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.

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 = 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.

#include <cmath>
class Solution {
public:
    int arrangeCoins(int n) {
        long long k = n;
        long long result = (sqrt(k * 8 + 1) - 1) / 2;
        return result;
    }
};

很典型的数学解法

#include <cmath>
class Solution {
public:
    int arrangeCoins(int n) {
        return 2 * (sqrt(n * 1.0 / 2 + 1.0 / 16) - 1.0 / 4);
    }
};

配凑的解法,二次方程求根公式的变形,保证不会出现超过整数范围(如果题目要求不能用更大范围整数的话)。

#include <cmath>
class Solution {
public:
    int arrangeCoins(int n) {
        int begin=0, end=n, mid;
        long long product;
        while(begin <= end)
        {
            mid = (begin+end)/2;
            product = (long long)mid*(mid+1)/2;
            if(product > n)
                end = mid -1;
            else if(product == n)
                return mid;
            else if(product < n)
                begin = mid+1;
        }
        return end;
    }
};

真的是强行二分!!!