Skip to content

Commit

Permalink
refactor: review Swift codes for chapter_computational_complexity art… (
Browse files Browse the repository at this point in the history
#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>
  • Loading branch information
nuomi1 and krahets authored Mar 3, 2023
1 parent dc72f8b commit 17ff091
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ func twoSumHashTable(nums: [Int], target: Int) -> [Int] {

@main
enum LeetcodeTwoSum {
/* Driver Code */
static func main() {
// ======= Test Case =======
let nums = [2, 7, 11, 15]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ func expRecur(n: Int) -> Int {
}

/* 对数阶(循环实现) */
func logarithmic(n: Int) -> Int {
func logarithmic(n: Double) -> Int {
var count = 0
var n = n
while n > 1 {
Expand All @@ -99,7 +99,7 @@ func logarithmic(n: Int) -> Int {
}

/* 对数阶(递归实现) */
func logRecur(n: Int) -> Int {
func logRecur(n: Double) -> Int {
if n <= 1 {
return 0
}
Expand All @@ -112,7 +112,7 @@ func linearLogRecur(n: Double) -> Int {
return 1
}
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
}
return count
Expand Down Expand Up @@ -158,9 +158,9 @@ enum TimeComplexity {
count = expRecur(n: n)
print("指数阶(递归实现)的计算操作数量 = \(count)")

count = logarithmic(n: n)
count = logarithmic(n: Double(n))
print("对数阶(循环实现)的计算操作数量 = \(count)")
count = logRecur(n: n)
count = logRecur(n: Double(n))
print("对数阶(递归实现)的计算操作数量 = \(count)")

count = linearLogRecur(n: Double(n))
Expand Down
8 changes: 4 additions & 4 deletions docs/chapter_computational_complexity/time_complexity.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ $$

```swift title=""
// 在某运行平台下
func algorithm(_ n: Int) {
func algorithm(n: Int) {
var a = 2 // 1 ns
a = a + 1 // 1 ns
a = a * 2 // 10 ns
Expand Down Expand Up @@ -340,19 +340,19 @@ $$

```swift title=""
// 算法 A 时间复杂度:常数阶
func algorithmA(_ n: Int) {
func algorithmA(n: Int) {
print(0)
}

// 算法 B 时间复杂度:线性阶
func algorithmB(_ n: Int) {
func algorithmB(n: Int) {
for _ in 0 ..< n {
print(0)
}
}

// 算法 C 时间复杂度:常数阶
func algorithmC(_ n: Int) {
func algorithmC(n: Int) {
for _ in 0 ..< 1000000 {
print(0)
}
Expand Down

0 comments on commit 17ff091

Please sign in to comment.