★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-qorqisgn-eh.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
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.git
Given n, find the total number of fullstaircase rows that can be formed.github
n is a non-negative integer and fits within the range of a 32-bit signed integer.微信
Example 1:spa
n = 5 The coins can form the following rows: ¤ ¤ ¤ ¤ ¤ Because the 3rd row is incomplete, we return 2.
Example 2:code
n = 8 The coins can form the following rows: ¤ ¤ ¤ ¤ ¤ ¤ ¤ ¤ Because the 4th row is incomplete, we return 3.
你總共有 n 枚硬幣,你須要將它們擺成一個階梯形狀,第 k 行就必須正好有 k 枚硬幣。orm
給定一個數字 n,找出可造成完整階梯行的總行數。htm
n 是一個非負整數,而且在32位有符號整型的範圍內。blog
示例 1:get
n = 5 硬幣可排列成如下幾行: ¤ ¤ ¤ ¤ ¤ 由於第三行不完整,因此返回2.
示例 2:
n = 8 硬幣可排列成如下幾行: ¤ ¤ ¤ ¤ ¤ ¤ ¤ ¤ 由於第四行不完整,因此返回3.
20ms
1 class Solution { 2 func arrangeCoins(_ n: Int) -> Int { 3 return Int((-1 + sqrt(Double(1 + 8 * n))) / 2) 4 } 5 }
28ms
1 class Solution { 2 func arrangeCoins(_ n: Int) -> Int { 3 guard n > 1 else { 4 return n 5 } 6 var index = n, lhs = 0, rhs = n, mid = 0 7 while lhs < rhs { 8 mid = (rhs + lhs) / 2 9 let result = (1 + mid) * mid / 2 10 if result == n { 11 return mid 12 } else if result > n { 13 rhs = mid 14 } else { 15 lhs = mid + 1 16 } 17 } 18 return lhs - 1 19 } 20 }
36ms
1 class Solution { 2 func arrangeCoins(_ n: Int) -> Int { 3 var left = 1 4 var right = n 5 6 while left <= right { 7 let mid = left + (right - left) / 2 8 if n * 2 < mid * (mid + 1) { 9 right = mid - 1 10 } else { 11 left = mid + 1 12 } 13 } 14 15 return left - 1 16 } 17 }
52ms
1 class Solution { 2 func arrangeCoins(_ n: Int) -> Int { 3 var result = Int(sqrt(Double(n * 2))) - 1 4 while result * (result + 1) / 2 <= n { 5 result += 1 6 } 7 return result - 1 8 } 9 }
80ms
1 class Solution { 2 func arrangeCoins(_ n: Int) -> Int { 3 var row = 1 4 var sum = row 5 while true { 6 if sum == n { 7 return row 8 } else if sum > n { 9 return row - 1 10 } 11 row += 1 12 sum += row 13 } 14 } 15 }
176ms
1 class Solution { 2 func arrangeCoins(_ n: Int) -> Int { 3 return self.lineCoins(n, 1) 4 } 5 func lineCoins(_ n: Int, _ line: Int) -> Int { 6 if n<line { 7 return line-1 8 } 9 return lineCoins(n-line, line+1); 10 } 11 }
204ms
1 class Solution { 2 func arrangeCoins(_ n: Int) -> Int { 3 if n == 0 || n == 1 { 4 return n 5 } 6 for value in 1...n { 7 if Double((1 + value) * value) * 0.5 > Double(n) { 8 return (value - 1) 9 } 10 } 11 return 0 12 } 13 }