138.Arranging Coins
阿新 • • 發佈:2018-09-05
code 其中 復雜 gin ins 當前 前行 開始 range
題目:
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(intn) { 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