refactor: review Swift codes for chapter_computational_complexity art… (#396)

* refactor: review Swift codes for chapter_computational_complexity articles

* Update time_complexity.swift

* Update time_complexity.swift

---------

Co-authored-by: Yudong Jin <krahets@163.com>
pull/405/head
nuomi1 2 years ago committed by GitHub
parent dc72f8b277
commit 17ff091a03
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -33,6 +33,7 @@ func twoSumHashTable(nums: [Int], target: Int) -> [Int] {
@main @main
enum LeetcodeTwoSum { enum LeetcodeTwoSum {
/* Driver Code */
static func main() { static func main() {
// ======= Test Case ======= // ======= Test Case =======
let nums = [2, 7, 11, 15] let nums = [2, 7, 11, 15]

@ -88,7 +88,7 @@ func expRecur(n: Int) -> Int {
} }
/* */ /* */
func logarithmic(n: Int) -> Int { func logarithmic(n: Double) -> Int {
var count = 0 var count = 0
var n = n var n = n
while n > 1 { while n > 1 {
@ -99,7 +99,7 @@ func logarithmic(n: Int) -> Int {
} }
/* */ /* */
func logRecur(n: Int) -> Int { func logRecur(n: Double) -> Int {
if n <= 1 { if n <= 1 {
return 0 return 0
} }
@ -112,7 +112,7 @@ func linearLogRecur(n: Double) -> Int {
return 1 return 1
} }
var count = linearLogRecur(n: n / 2) + linearLogRecur(n: n / 2) var count = linearLogRecur(n: n / 2) + linearLogRecur(n: n / 2)
for _ in 0 ..< Int(n) { for _ in sequence(first: 0, next: { $0 < n - 1 ? $0 + 1 : nil }) {
count += 1 count += 1
} }
return count return count
@ -158,9 +158,9 @@ enum TimeComplexity {
count = expRecur(n: n) count = expRecur(n: n)
print("指数阶(递归实现)的计算操作数量 = \(count)") print("指数阶(递归实现)的计算操作数量 = \(count)")
count = logarithmic(n: n) count = logarithmic(n: Double(n))
print("对数阶(循环实现)的计算操作数量 = \(count)") print("对数阶(循环实现)的计算操作数量 = \(count)")
count = logRecur(n: n) count = logRecur(n: Double(n))
print("对数阶(递归实现)的计算操作数量 = \(count)") print("对数阶(递归实现)的计算操作数量 = \(count)")
count = linearLogRecur(n: Double(n)) count = linearLogRecur(n: Double(n))

@ -138,7 +138,7 @@ $$
```swift title="" ```swift title=""
// 在某运行平台下 // 在某运行平台下
func algorithm(_ n: Int) { func algorithm(n: Int) {
var a = 2 // 1 ns var a = 2 // 1 ns
a = a + 1 // 1 ns a = a + 1 // 1 ns
a = a * 2 // 10 ns a = a * 2 // 10 ns
@ -340,19 +340,19 @@ $$
```swift title="" ```swift title=""
// 算法 A 时间复杂度:常数阶 // 算法 A 时间复杂度:常数阶
func algorithmA(_ n: Int) { func algorithmA(n: Int) {
print(0) print(0)
} }
// 算法 B 时间复杂度:线性阶 // 算法 B 时间复杂度:线性阶
func algorithmB(_ n: Int) { func algorithmB(n: Int) {
for _ in 0 ..< n { for _ in 0 ..< n {
print(0) print(0)
} }
} }
// 算法 C 时间复杂度:常数阶 // 算法 C 时间复杂度:常数阶
func algorithmC(_ n: Int) { func algorithmC(n: Int) {
for _ in 0 ..< 1000000 { for _ in 0 ..< 1000000 {
print(0) print(0)
} }

Loading…
Cancel
Save