mirror of
https://github.com/krahets/hello-algo.git
synced 2026-08-31 12:27:13 +00:00
Translate all code to English (#1836)
* Review the EN heading format. * Fix pythontutor headings. * Fix pythontutor headings. * bug fixes * Fix headings in **/summary.md * Revisit the CN-to-EN translation for Python code using Claude-4.5 * Revisit the CN-to-EN translation for Java code using Claude-4.5 * Revisit the CN-to-EN translation for Cpp code using Claude-4.5. * Fix the dictionary. * Fix cpp code translation for the multipart strings. * Translate Go code to English. * Update workflows to test EN code. * Add EN translation for C. * Add EN translation for CSharp. * Add EN translation for Swift. * Trigger the CI check. * Revert. * Update en/hash_map.md * Add the EN version of Dart code. * Add the EN version of Kotlin code. * Add missing code files. * Add the EN version of JavaScript code. * Add the EN version of TypeScript code. * Fix the workflows. * Add the EN version of Ruby code. * Add the EN version of Rust code. * Update the CI check for the English version code. * Update Python CI check. * Fix cmakelists for en/C code. * Fix Ruby comments
This commit is contained in:
@@ -0,0 +1,130 @@
|
||||
# Created by https://www.toptal.com/developers/gitignore/api/objective-c,swift,swiftpackagemanager
|
||||
# Edit at https://www.toptal.com/developers/gitignore?templates=objective-c,swift,swiftpackagemanager
|
||||
|
||||
### Objective-C ###
|
||||
# Xcode
|
||||
#
|
||||
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
|
||||
|
||||
## User settings
|
||||
xcuserdata/
|
||||
|
||||
## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9)
|
||||
*.xcscmblueprint
|
||||
*.xccheckout
|
||||
|
||||
## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4)
|
||||
build/
|
||||
DerivedData/
|
||||
*.moved-aside
|
||||
*.pbxuser
|
||||
!default.pbxuser
|
||||
*.mode1v3
|
||||
!default.mode1v3
|
||||
*.mode2v3
|
||||
!default.mode2v3
|
||||
*.perspectivev3
|
||||
!default.perspectivev3
|
||||
|
||||
## Obj-C/Swift specific
|
||||
*.hmap
|
||||
|
||||
## App packaging
|
||||
*.ipa
|
||||
*.dSYM.zip
|
||||
*.dSYM
|
||||
|
||||
# CocoaPods
|
||||
# We recommend against adding the Pods directory to your .gitignore. However
|
||||
# you should judge for yourself, the pros and cons are mentioned at:
|
||||
# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
|
||||
# Pods/
|
||||
# Add this line if you want to avoid checking in source code from the Xcode workspace
|
||||
# *.xcworkspace
|
||||
|
||||
# Carthage
|
||||
# Add this line if you want to avoid checking in source code from Carthage dependencies.
|
||||
# Carthage/Checkouts
|
||||
|
||||
Carthage/Build/
|
||||
|
||||
# fastlane
|
||||
# It is recommended to not store the screenshots in the git repo.
|
||||
# Instead, use fastlane to re-generate the screenshots whenever they are needed.
|
||||
# For more information about the recommended setup visit:
|
||||
# https://docs.fastlane.tools/best-practices/source-control/#source-control
|
||||
|
||||
fastlane/report.xml
|
||||
fastlane/Preview.html
|
||||
fastlane/screenshots/**/*.png
|
||||
fastlane/test_output
|
||||
|
||||
# Code Injection
|
||||
# After new code Injection tools there's a generated folder /iOSInjectionProject
|
||||
# https://github.com/johnno1962/injectionforxcode
|
||||
|
||||
iOSInjectionProject/
|
||||
|
||||
### Objective-C Patch ###
|
||||
|
||||
### Swift ###
|
||||
# Xcode
|
||||
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
## Playgrounds
|
||||
timeline.xctimeline
|
||||
playground.xcworkspace
|
||||
|
||||
# Swift Package Manager
|
||||
# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies.
|
||||
# Packages/
|
||||
# Package.pins
|
||||
# Package.resolved
|
||||
# *.xcodeproj
|
||||
# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata
|
||||
# hence it is not needed unless you have added a package configuration file to your project
|
||||
# .swiftpm
|
||||
|
||||
.build/
|
||||
|
||||
# CocoaPods
|
||||
# We recommend against adding the Pods directory to your .gitignore. However
|
||||
# you should judge for yourself, the pros and cons are mentioned at:
|
||||
# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
|
||||
# Pods/
|
||||
# Add this line if you want to avoid checking in source code from the Xcode workspace
|
||||
# *.xcworkspace
|
||||
|
||||
# Carthage
|
||||
# Add this line if you want to avoid checking in source code from Carthage dependencies.
|
||||
# Carthage/Checkouts
|
||||
|
||||
|
||||
# Accio dependency management
|
||||
Dependencies/
|
||||
.accio/
|
||||
|
||||
# fastlane
|
||||
# It is recommended to not store the screenshots in the git repo.
|
||||
# Instead, use fastlane to re-generate the screenshots whenever they are needed.
|
||||
# For more information about the recommended setup visit:
|
||||
# https://docs.fastlane.tools/best-practices/source-control/#source-control
|
||||
|
||||
|
||||
# Code Injection
|
||||
# After new code Injection tools there's a generated folder /iOSInjectionProject
|
||||
# https://github.com/johnno1962/injectionforxcode
|
||||
|
||||
|
||||
### SwiftPackageManager ###
|
||||
Packages
|
||||
xcuserdata
|
||||
*.xcodeproj
|
||||
|
||||
|
||||
# End of https://www.toptal.com/developers/gitignore/api/objective-c,swift,swiftpackagemanager
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "swift-collections",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/apple/swift-collections",
|
||||
"state" : {
|
||||
"branch" : "release/1.1",
|
||||
"revision" : "4a1d92ba85027010d2c528c05576cde9a362254b"
|
||||
}
|
||||
}
|
||||
],
|
||||
"version" : 2
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
// swift-tools-version: 5.7
|
||||
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "HelloAlgo",
|
||||
products: [
|
||||
// chapter_computational_complexity
|
||||
.executable(name: "iteration", targets: ["iteration"]),
|
||||
.executable(name: "recursion", targets: ["recursion"]),
|
||||
.executable(name: "time_complexity", targets: ["time_complexity"]),
|
||||
.executable(name: "worst_best_time_complexity", targets: ["worst_best_time_complexity"]),
|
||||
.executable(name: "space_complexity", targets: ["space_complexity"]),
|
||||
// chapter_array_and_linkedlist
|
||||
.executable(name: "array", targets: ["array"]),
|
||||
.executable(name: "linked_list", targets: ["linked_list"]),
|
||||
.executable(name: "list", targets: ["list"]),
|
||||
.executable(name: "my_list", targets: ["my_list"]),
|
||||
// chapter_stack_and_queue
|
||||
.executable(name: "stack", targets: ["stack"]),
|
||||
.executable(name: "linkedlist_stack", targets: ["linkedlist_stack"]),
|
||||
.executable(name: "array_stack", targets: ["array_stack"]),
|
||||
.executable(name: "queue", targets: ["queue"]),
|
||||
.executable(name: "linkedlist_queue", targets: ["linkedlist_queue"]),
|
||||
.executable(name: "array_queue", targets: ["array_queue"]),
|
||||
.executable(name: "deque", targets: ["deque"]),
|
||||
.executable(name: "linkedlist_deque", targets: ["linkedlist_deque"]),
|
||||
.executable(name: "array_deque", targets: ["array_deque"]),
|
||||
// chapter_hashing
|
||||
.executable(name: "hash_map", targets: ["hash_map"]),
|
||||
.executable(name: "array_hash_map", targets: ["array_hash_map"]),
|
||||
.executable(name: "hash_map_chaining", targets: ["hash_map_chaining"]),
|
||||
.executable(name: "hash_map_open_addressing", targets: ["hash_map_open_addressing"]),
|
||||
.executable(name: "simple_hash", targets: ["simple_hash"]),
|
||||
.executable(name: "built_in_hash", targets: ["built_in_hash"]),
|
||||
// chapter_tree
|
||||
.executable(name: "binary_tree", targets: ["binary_tree"]),
|
||||
.executable(name: "binary_tree_bfs", targets: ["binary_tree_bfs"]),
|
||||
.executable(name: "binary_tree_dfs", targets: ["binary_tree_dfs"]),
|
||||
.executable(name: "array_binary_tree", targets: ["array_binary_tree"]),
|
||||
.executable(name: "binary_search_tree", targets: ["binary_search_tree"]),
|
||||
.executable(name: "avl_tree", targets: ["avl_tree"]),
|
||||
// chapter_heap
|
||||
.executable(name: "heap", targets: ["heap"]),
|
||||
.executable(name: "my_heap", targets: ["my_heap"]),
|
||||
.executable(name: "top_k", targets: ["top_k"]),
|
||||
// chapter_graph
|
||||
.executable(name: "graph_adjacency_matrix", targets: ["graph_adjacency_matrix"]),
|
||||
.executable(name: "graph_adjacency_list", targets: ["graph_adjacency_list"]),
|
||||
.executable(name: "graph_bfs", targets: ["graph_bfs"]),
|
||||
.executable(name: "graph_dfs", targets: ["graph_dfs"]),
|
||||
// chapter_searching
|
||||
.executable(name: "binary_search", targets: ["binary_search"]),
|
||||
.executable(name: "binary_search_insertion", targets: ["binary_search_insertion"]),
|
||||
.executable(name: "binary_search_edge", targets: ["binary_search_edge"]),
|
||||
.executable(name: "two_sum", targets: ["two_sum"]),
|
||||
.executable(name: "linear_search", targets: ["linear_search"]),
|
||||
.executable(name: "hashing_search", targets: ["hashing_search"]),
|
||||
// chapter_sorting
|
||||
.executable(name: "selection_sort", targets: ["selection_sort"]),
|
||||
.executable(name: "bubble_sort", targets: ["bubble_sort"]),
|
||||
.executable(name: "insertion_sort", targets: ["insertion_sort"]),
|
||||
.executable(name: "quick_sort", targets: ["quick_sort"]),
|
||||
.executable(name: "merge_sort", targets: ["merge_sort"]),
|
||||
.executable(name: "heap_sort", targets: ["heap_sort"]),
|
||||
.executable(name: "bucket_sort", targets: ["bucket_sort"]),
|
||||
.executable(name: "counting_sort", targets: ["counting_sort"]),
|
||||
.executable(name: "radix_sort", targets: ["radix_sort"]),
|
||||
// chapter_divide_and_conquer
|
||||
.executable(name: "binary_search_recur", targets: ["binary_search_recur"]),
|
||||
.executable(name: "build_tree", targets: ["build_tree"]),
|
||||
.executable(name: "hanota", targets: ["hanota"]),
|
||||
// chapter_backtracking
|
||||
.executable(name: "preorder_traversal_i_compact", targets: ["preorder_traversal_i_compact"]),
|
||||
.executable(name: "preorder_traversal_ii_compact", targets: ["preorder_traversal_ii_compact"]),
|
||||
.executable(name: "preorder_traversal_iii_compact", targets: ["preorder_traversal_iii_compact"]),
|
||||
.executable(name: "preorder_traversal_iii_template", targets: ["preorder_traversal_iii_template"]),
|
||||
.executable(name: "permutations_i", targets: ["permutations_i"]),
|
||||
.executable(name: "permutations_ii", targets: ["permutations_ii"]),
|
||||
.executable(name: "subset_sum_i_naive", targets: ["subset_sum_i_naive"]),
|
||||
.executable(name: "subset_sum_i", targets: ["subset_sum_i"]),
|
||||
.executable(name: "subset_sum_ii", targets: ["subset_sum_ii"]),
|
||||
.executable(name: "n_queens", targets: ["n_queens"]),
|
||||
// chapter_dynamic_programming
|
||||
.executable(name: "climbing_stairs_backtrack", targets: ["climbing_stairs_backtrack"]),
|
||||
.executable(name: "climbing_stairs_dfs", targets: ["climbing_stairs_dfs"]),
|
||||
.executable(name: "climbing_stairs_dfs_mem", targets: ["climbing_stairs_dfs_mem"]),
|
||||
.executable(name: "climbing_stairs_dp", targets: ["climbing_stairs_dp"]),
|
||||
.executable(name: "min_cost_climbing_stairs_dp", targets: ["min_cost_climbing_stairs_dp"]),
|
||||
.executable(name: "climbing_stairs_constraint_dp", targets: ["climbing_stairs_constraint_dp"]),
|
||||
.executable(name: "min_path_sum", targets: ["min_path_sum"]),
|
||||
.executable(name: "knapsack", targets: ["knapsack"]),
|
||||
.executable(name: "unbounded_knapsack", targets: ["unbounded_knapsack"]),
|
||||
.executable(name: "coin_change", targets: ["coin_change"]),
|
||||
.executable(name: "coin_change_ii", targets: ["coin_change_ii"]),
|
||||
.executable(name: "edit_distance", targets: ["edit_distance"]),
|
||||
// chapter_greedy
|
||||
.executable(name: "coin_change_greedy", targets: ["coin_change_greedy"]),
|
||||
.executable(name: "fractional_knapsack", targets: ["fractional_knapsack"]),
|
||||
.executable(name: "max_capacity", targets: ["max_capacity"]),
|
||||
.executable(name: "max_product_cutting", targets: ["max_product_cutting"]),
|
||||
],
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/apple/swift-collections", branch: "release/1.1"),
|
||||
],
|
||||
targets: [
|
||||
// helper
|
||||
.target(name: "utils", path: "utils"),
|
||||
.target(name: "graph_adjacency_list_target", dependencies: ["utils"], path: "chapter_graph", sources: ["graph_adjacency_list_target.swift"], swiftSettings: [.define("TARGET")]),
|
||||
.target(name: "binary_search_insertion_target", path: "chapter_searching", sources: ["binary_search_insertion_target.swift"], swiftSettings: [.define("TARGET")]),
|
||||
// chapter_computational_complexity
|
||||
.executableTarget(name: "iteration", path: "chapter_computational_complexity", sources: ["iteration.swift"]),
|
||||
.executableTarget(name: "recursion", path: "chapter_computational_complexity", sources: ["recursion.swift"]),
|
||||
.executableTarget(name: "time_complexity", path: "chapter_computational_complexity", sources: ["time_complexity.swift"]),
|
||||
.executableTarget(name: "worst_best_time_complexity", path: "chapter_computational_complexity", sources: ["worst_best_time_complexity.swift"]),
|
||||
.executableTarget(name: "space_complexity", dependencies: ["utils"], path: "chapter_computational_complexity", sources: ["space_complexity.swift"]),
|
||||
// chapter_array_and_linkedlist
|
||||
.executableTarget(name: "array", path: "chapter_array_and_linkedlist", sources: ["array.swift"]),
|
||||
.executableTarget(name: "linked_list", dependencies: ["utils"], path: "chapter_array_and_linkedlist", sources: ["linked_list.swift"]),
|
||||
.executableTarget(name: "list", path: "chapter_array_and_linkedlist", sources: ["list.swift"]),
|
||||
.executableTarget(name: "my_list", path: "chapter_array_and_linkedlist", sources: ["my_list.swift"]),
|
||||
// chapter_stack_and_queue
|
||||
.executableTarget(name: "stack", path: "chapter_stack_and_queue", sources: ["stack.swift"]),
|
||||
.executableTarget(name: "linkedlist_stack", dependencies: ["utils"], path: "chapter_stack_and_queue", sources: ["linkedlist_stack.swift"]),
|
||||
.executableTarget(name: "array_stack", path: "chapter_stack_and_queue", sources: ["array_stack.swift"]),
|
||||
.executableTarget(name: "queue", path: "chapter_stack_and_queue", sources: ["queue.swift"]),
|
||||
.executableTarget(name: "linkedlist_queue", dependencies: ["utils"], path: "chapter_stack_and_queue", sources: ["linkedlist_queue.swift"]),
|
||||
.executableTarget(name: "array_queue", path: "chapter_stack_and_queue", sources: ["array_queue.swift"]),
|
||||
.executableTarget(name: "deque", path: "chapter_stack_and_queue", sources: ["deque.swift"]),
|
||||
.executableTarget(name: "linkedlist_deque", path: "chapter_stack_and_queue", sources: ["linkedlist_deque.swift"]),
|
||||
.executableTarget(name: "array_deque", path: "chapter_stack_and_queue", sources: ["array_deque.swift"]),
|
||||
// chapter_hashing
|
||||
.executableTarget(name: "hash_map", dependencies: ["utils"], path: "chapter_hashing", sources: ["hash_map.swift"]),
|
||||
.executableTarget(name: "array_hash_map", dependencies: ["utils"], path: "chapter_hashing", sources: ["array_hash_map.swift"]),
|
||||
.executableTarget(name: "hash_map_chaining", dependencies: ["utils"], path: "chapter_hashing", sources: ["hash_map_chaining.swift"]),
|
||||
.executableTarget(name: "hash_map_open_addressing", dependencies: ["utils"], path: "chapter_hashing", sources: ["hash_map_open_addressing.swift"]),
|
||||
.executableTarget(name: "simple_hash", path: "chapter_hashing", sources: ["simple_hash.swift"]),
|
||||
.executableTarget(name: "built_in_hash", dependencies: ["utils"], path: "chapter_hashing", sources: ["built_in_hash.swift"]),
|
||||
// chapter_tree
|
||||
.executableTarget(name: "binary_tree", dependencies: ["utils"], path: "chapter_tree", sources: ["binary_tree.swift"]),
|
||||
.executableTarget(name: "binary_tree_bfs", dependencies: ["utils"], path: "chapter_tree", sources: ["binary_tree_bfs.swift"]),
|
||||
.executableTarget(name: "binary_tree_dfs", dependencies: ["utils"], path: "chapter_tree", sources: ["binary_tree_dfs.swift"]),
|
||||
.executableTarget(name: "array_binary_tree", dependencies: ["utils"], path: "chapter_tree", sources: ["array_binary_tree.swift"]),
|
||||
.executableTarget(name: "binary_search_tree", dependencies: ["utils"], path: "chapter_tree", sources: ["binary_search_tree.swift"]),
|
||||
.executableTarget(name: "avl_tree", dependencies: ["utils"], path: "chapter_tree", sources: ["avl_tree.swift"]),
|
||||
// chapter_heap
|
||||
.executableTarget(name: "heap", dependencies: ["utils", .product(name: "HeapModule", package: "swift-collections")], path: "chapter_heap", sources: ["heap.swift"]),
|
||||
.executableTarget(name: "my_heap", dependencies: ["utils"], path: "chapter_heap", sources: ["my_heap.swift"]),
|
||||
.executableTarget(name: "top_k", dependencies: ["utils", .product(name: "HeapModule", package: "swift-collections")], path: "chapter_heap", sources: ["top_k.swift"]),
|
||||
// chapter_graph
|
||||
.executableTarget(name: "graph_adjacency_matrix", dependencies: ["utils"], path: "chapter_graph", sources: ["graph_adjacency_matrix.swift"]),
|
||||
.executableTarget(name: "graph_adjacency_list", dependencies: ["utils"], path: "chapter_graph", sources: ["graph_adjacency_list.swift"]),
|
||||
.executableTarget(name: "graph_bfs", dependencies: ["utils", "graph_adjacency_list_target"], path: "chapter_graph", sources: ["graph_bfs.swift"]),
|
||||
.executableTarget(name: "graph_dfs", dependencies: ["utils", "graph_adjacency_list_target"], path: "chapter_graph", sources: ["graph_dfs.swift"]),
|
||||
// chapter_searching
|
||||
.executableTarget(name: "binary_search", path: "chapter_searching", sources: ["binary_search.swift"]),
|
||||
.executableTarget(name: "binary_search_insertion", path: "chapter_searching", sources: ["binary_search_insertion.swift"]),
|
||||
.executableTarget(name: "binary_search_edge", dependencies: ["binary_search_insertion_target"], path: "chapter_searching", sources: ["binary_search_edge.swift"]),
|
||||
.executableTarget(name: "two_sum", path: "chapter_searching", sources: ["two_sum.swift"]),
|
||||
.executableTarget(name: "linear_search", dependencies: ["utils"], path: "chapter_searching", sources: ["linear_search.swift"]),
|
||||
.executableTarget(name: "hashing_search", dependencies: ["utils"], path: "chapter_searching", sources: ["hashing_search.swift"]),
|
||||
// chapter_sorting
|
||||
.executableTarget(name: "selection_sort", path: "chapter_sorting", sources: ["selection_sort.swift"]),
|
||||
.executableTarget(name: "bubble_sort", path: "chapter_sorting", sources: ["bubble_sort.swift"]),
|
||||
.executableTarget(name: "insertion_sort", path: "chapter_sorting", sources: ["insertion_sort.swift"]),
|
||||
.executableTarget(name: "quick_sort", path: "chapter_sorting", sources: ["quick_sort.swift"]),
|
||||
.executableTarget(name: "merge_sort", path: "chapter_sorting", sources: ["merge_sort.swift"]),
|
||||
.executableTarget(name: "heap_sort", path: "chapter_sorting", sources: ["heap_sort.swift"]),
|
||||
.executableTarget(name: "bucket_sort", path: "chapter_sorting", sources: ["bucket_sort.swift"]),
|
||||
.executableTarget(name: "counting_sort", path: "chapter_sorting", sources: ["counting_sort.swift"]),
|
||||
.executableTarget(name: "radix_sort", path: "chapter_sorting", sources: ["radix_sort.swift"]),
|
||||
// chapter_divide_and_conquer
|
||||
.executableTarget(name: "binary_search_recur", path: "chapter_divide_and_conquer", sources: ["binary_search_recur.swift"]),
|
||||
.executableTarget(name: "build_tree", dependencies: ["utils"], path: "chapter_divide_and_conquer", sources: ["build_tree.swift"]),
|
||||
.executableTarget(name: "hanota", path: "chapter_divide_and_conquer", sources: ["hanota.swift"]),
|
||||
// chapter_backtracking
|
||||
.executableTarget(name: "preorder_traversal_i_compact", dependencies: ["utils"], path: "chapter_backtracking", sources: ["preorder_traversal_i_compact.swift"]),
|
||||
.executableTarget(name: "preorder_traversal_ii_compact", dependencies: ["utils"], path: "chapter_backtracking", sources: ["preorder_traversal_ii_compact.swift"]),
|
||||
.executableTarget(name: "preorder_traversal_iii_compact", dependencies: ["utils"], path: "chapter_backtracking", sources: ["preorder_traversal_iii_compact.swift"]),
|
||||
.executableTarget(name: "preorder_traversal_iii_template", dependencies: ["utils"], path: "chapter_backtracking", sources: ["preorder_traversal_iii_template.swift"]),
|
||||
.executableTarget(name: "permutations_i", path: "chapter_backtracking", sources: ["permutations_i.swift"]),
|
||||
.executableTarget(name: "permutations_ii", path: "chapter_backtracking", sources: ["permutations_ii.swift"]),
|
||||
.executableTarget(name: "subset_sum_i_naive", path: "chapter_backtracking", sources: ["subset_sum_i_naive.swift"]),
|
||||
.executableTarget(name: "subset_sum_i", path: "chapter_backtracking", sources: ["subset_sum_i.swift"]),
|
||||
.executableTarget(name: "subset_sum_ii", path: "chapter_backtracking", sources: ["subset_sum_ii.swift"]),
|
||||
.executableTarget(name: "n_queens", path: "chapter_backtracking", sources: ["n_queens.swift"]),
|
||||
// chapter_dynamic_programming
|
||||
.executableTarget(name: "climbing_stairs_backtrack", path: "chapter_dynamic_programming", sources: ["climbing_stairs_backtrack.swift"]),
|
||||
.executableTarget(name: "climbing_stairs_dfs", path: "chapter_dynamic_programming", sources: ["climbing_stairs_dfs.swift"]),
|
||||
.executableTarget(name: "climbing_stairs_dfs_mem", path: "chapter_dynamic_programming", sources: ["climbing_stairs_dfs_mem.swift"]),
|
||||
.executableTarget(name: "climbing_stairs_dp", path: "chapter_dynamic_programming", sources: ["climbing_stairs_dp.swift"]),
|
||||
.executableTarget(name: "min_cost_climbing_stairs_dp", path: "chapter_dynamic_programming", sources: ["min_cost_climbing_stairs_dp.swift"]),
|
||||
.executableTarget(name: "climbing_stairs_constraint_dp", path: "chapter_dynamic_programming", sources: ["climbing_stairs_constraint_dp.swift"]),
|
||||
.executableTarget(name: "min_path_sum", path: "chapter_dynamic_programming", sources: ["min_path_sum.swift"]),
|
||||
.executableTarget(name: "knapsack", path: "chapter_dynamic_programming", sources: ["knapsack.swift"]),
|
||||
.executableTarget(name: "unbounded_knapsack", path: "chapter_dynamic_programming", sources: ["unbounded_knapsack.swift"]),
|
||||
.executableTarget(name: "coin_change", path: "chapter_dynamic_programming", sources: ["coin_change.swift"]),
|
||||
.executableTarget(name: "coin_change_ii", path: "chapter_dynamic_programming", sources: ["coin_change_ii.swift"]),
|
||||
.executableTarget(name: "edit_distance", path: "chapter_dynamic_programming", sources: ["edit_distance.swift"]),
|
||||
// chapter_greedy
|
||||
.executableTarget(name: "coin_change_greedy", path: "chapter_greedy", sources: ["coin_change_greedy.swift"]),
|
||||
.executableTarget(name: "fractional_knapsack", path: "chapter_greedy", sources: ["fractional_knapsack.swift"]),
|
||||
.executableTarget(name: "max_capacity", path: "chapter_greedy", sources: ["max_capacity.swift"]),
|
||||
.executableTarget(name: "max_product_cutting", path: "chapter_greedy", sources: ["max_product_cutting.swift"]),
|
||||
]
|
||||
)
|
||||
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* File: array.swift
|
||||
* Created Time: 2023-01-05
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Random access to element */
|
||||
func randomAccess(nums: [Int]) -> Int {
|
||||
// Randomly select a number in interval [0, nums.count)
|
||||
let randomIndex = nums.indices.randomElement()!
|
||||
// Retrieve and return the random element
|
||||
let randomNum = nums[randomIndex]
|
||||
return randomNum
|
||||
}
|
||||
|
||||
/* Extend array length */
|
||||
func extend(nums: [Int], enlarge: Int) -> [Int] {
|
||||
// Initialize an array with extended length
|
||||
var res = Array(repeating: 0, count: nums.count + enlarge)
|
||||
// Copy all elements from the original array to the new array
|
||||
for i in nums.indices {
|
||||
res[i] = nums[i]
|
||||
}
|
||||
// Return the extended new array
|
||||
return res
|
||||
}
|
||||
|
||||
/* Insert element num at index index in the array */
|
||||
func insert(nums: inout [Int], num: Int, index: Int) {
|
||||
// Move all elements at and after index index backward by one position
|
||||
for i in nums.indices.dropFirst(index).reversed() {
|
||||
nums[i] = nums[i - 1]
|
||||
}
|
||||
// Assign num to the element at index index
|
||||
nums[index] = num
|
||||
}
|
||||
|
||||
/* Remove the element at index index */
|
||||
func remove(nums: inout [Int], index: Int) {
|
||||
// Move all elements after index index forward by one position
|
||||
for i in nums.indices.dropFirst(index).dropLast() {
|
||||
nums[i] = nums[i + 1]
|
||||
}
|
||||
}
|
||||
|
||||
/* Traverse array */
|
||||
func traverse(nums: [Int]) {
|
||||
var count = 0
|
||||
// Traverse array by index
|
||||
for i in nums.indices {
|
||||
count += nums[i]
|
||||
}
|
||||
// Direct traversal of array elements
|
||||
for num in nums {
|
||||
count += num
|
||||
}
|
||||
// Traverse simultaneously data index and elements
|
||||
for (i, num) in nums.enumerated() {
|
||||
count += nums[i]
|
||||
count += num
|
||||
}
|
||||
}
|
||||
|
||||
/* Find the specified element in the array */
|
||||
func find(nums: [Int], target: Int) -> Int {
|
||||
for i in nums.indices {
|
||||
if nums[i] == target {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
@main
|
||||
enum _Array {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
/* Initialize array */
|
||||
let arr = Array(repeating: 0, count: 5)
|
||||
print("Array arr = \(arr)")
|
||||
var nums = [1, 3, 2, 5, 4]
|
||||
print("Array nums = \(nums)")
|
||||
|
||||
/* Insert element */
|
||||
let randomNum = randomAccess(nums: nums)
|
||||
print("Get random element \(randomNum) from nums")
|
||||
|
||||
/* Traverse array */
|
||||
nums = extend(nums: nums, enlarge: 3)
|
||||
print("Extend array length to 8, get nums = \(nums)")
|
||||
|
||||
/* Insert element */
|
||||
insert(nums: &nums, num: 6, index: 3)
|
||||
print("Insert number 6 at index 3, get nums = \(nums)")
|
||||
|
||||
/* Remove element */
|
||||
remove(nums: &nums, index: 2)
|
||||
print("Delete element at index 2, get nums = \(nums)")
|
||||
|
||||
/* Traverse array */
|
||||
traverse(nums: nums)
|
||||
|
||||
/* Find element */
|
||||
let index = find(nums: nums, target: 3)
|
||||
print("Find element 3 in nums, index = \(index)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* File: linked_list.swift
|
||||
* Created Time: 2023-01-08
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
import utils
|
||||
|
||||
/* Insert node P after node n0 in the linked list */
|
||||
func insert(n0: ListNode, P: ListNode) {
|
||||
let n1 = n0.next
|
||||
P.next = n1
|
||||
n0.next = P
|
||||
}
|
||||
|
||||
/* Remove the first node after node n0 in the linked list */
|
||||
func remove(n0: ListNode) {
|
||||
if n0.next == nil {
|
||||
return
|
||||
}
|
||||
// n0 -> P -> n1
|
||||
let P = n0.next
|
||||
let n1 = P?.next
|
||||
n0.next = n1
|
||||
}
|
||||
|
||||
/* Access the node at index index in the linked list */
|
||||
func access(head: ListNode, index: Int) -> ListNode? {
|
||||
var head: ListNode? = head
|
||||
for _ in 0 ..< index {
|
||||
if head == nil {
|
||||
return nil
|
||||
}
|
||||
head = head?.next
|
||||
}
|
||||
return head
|
||||
}
|
||||
|
||||
/* Find the first node with value target in the linked list */
|
||||
func find(head: ListNode, target: Int) -> Int {
|
||||
var head: ListNode? = head
|
||||
var index = 0
|
||||
while head != nil {
|
||||
if head?.val == target {
|
||||
return index
|
||||
}
|
||||
head = head?.next
|
||||
index += 1
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
@main
|
||||
enum LinkedList {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
/* Initialize linked list */
|
||||
// Initialize each node
|
||||
let n0 = ListNode(x: 1)
|
||||
let n1 = ListNode(x: 3)
|
||||
let n2 = ListNode(x: 2)
|
||||
let n3 = ListNode(x: 5)
|
||||
let n4 = ListNode(x: 4)
|
||||
// Build references between nodes
|
||||
n0.next = n1
|
||||
n1.next = n2
|
||||
n2.next = n3
|
||||
n3.next = n4
|
||||
print("Initialized linked list is")
|
||||
PrintUtil.printLinkedList(head: n0)
|
||||
|
||||
/* Insert node */
|
||||
insert(n0: n0, P: ListNode(x: 0))
|
||||
print("Linked list after inserting node is")
|
||||
PrintUtil.printLinkedList(head: n0)
|
||||
|
||||
/* Remove node */
|
||||
remove(n0: n0)
|
||||
print("Linked list after removing node is")
|
||||
PrintUtil.printLinkedList(head: n0)
|
||||
|
||||
/* Access node */
|
||||
let node = access(head: n0, index: 3)
|
||||
print("Value of node at index 3 in linked list = \(node!.val)")
|
||||
|
||||
/* Search node */
|
||||
let index = find(head: n0, target: 2)
|
||||
print("Index of node with value 2 in linked list = \(index)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* File: list.swift
|
||||
* Created Time: 2023-01-08
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
@main
|
||||
enum List {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
/* Initialize list */
|
||||
var nums = [1, 3, 2, 5, 4]
|
||||
print("List nums = \(nums)")
|
||||
|
||||
/* Update element */
|
||||
let num = nums[1]
|
||||
print("Access element at index 1, get num = \(num)")
|
||||
|
||||
/* Add elements at the end */
|
||||
nums[1] = 0
|
||||
print("Update element at index 1 to 0, get nums = \(nums)")
|
||||
|
||||
/* Remove element */
|
||||
nums.removeAll()
|
||||
print("After clearing list, nums = \(nums)")
|
||||
|
||||
/* Direct traversal of list elements */
|
||||
nums.append(1)
|
||||
nums.append(3)
|
||||
nums.append(2)
|
||||
nums.append(5)
|
||||
nums.append(4)
|
||||
print("After adding elements, nums = \(nums)")
|
||||
|
||||
/* Sort list */
|
||||
nums.insert(6, at: 3)
|
||||
print("Insert number 6 at index 3, get nums = \(nums)")
|
||||
|
||||
/* Remove element */
|
||||
nums.remove(at: 3)
|
||||
print("Delete element at index 3, get nums = \(nums)")
|
||||
|
||||
/* Traverse list by index */
|
||||
var count = 0
|
||||
for i in nums.indices {
|
||||
count += nums[i]
|
||||
}
|
||||
/* Directly traverse list elements */
|
||||
count = 0
|
||||
for x in nums {
|
||||
count += x
|
||||
}
|
||||
|
||||
/* Concatenate two lists */
|
||||
let nums1 = [6, 8, 7, 10, 9]
|
||||
nums.append(contentsOf: nums1)
|
||||
print("After concatenating list nums1 to nums, get nums = \(nums)")
|
||||
|
||||
/* Sort list */
|
||||
nums.sort()
|
||||
print("After sorting list, nums = \(nums)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* File: my_list.swift
|
||||
* Created Time: 2023-01-08
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* List class */
|
||||
class MyList {
|
||||
private var arr: [Int] // Array (stores list elements)
|
||||
private var _capacity: Int // List capacity
|
||||
private var _size: Int // List length (current number of elements)
|
||||
private let extendRatio: Int // Multiple by which the list capacity is extended each time
|
||||
|
||||
/* Constructor */
|
||||
init() {
|
||||
_capacity = 10
|
||||
_size = 0
|
||||
extendRatio = 2
|
||||
arr = Array(repeating: 0, count: _capacity)
|
||||
}
|
||||
|
||||
/* Get list length (current number of elements) */
|
||||
func size() -> Int {
|
||||
_size
|
||||
}
|
||||
|
||||
/* Get list capacity */
|
||||
func capacity() -> Int {
|
||||
_capacity
|
||||
}
|
||||
|
||||
/* Update element */
|
||||
func get(index: Int) -> Int {
|
||||
// Throw error if index out of bounds, same below
|
||||
if index < 0 || index >= size() {
|
||||
fatalError("Index out of bounds")
|
||||
}
|
||||
return arr[index]
|
||||
}
|
||||
|
||||
/* Add elements at the end */
|
||||
func set(index: Int, num: Int) {
|
||||
if index < 0 || index >= size() {
|
||||
fatalError("Index out of bounds")
|
||||
}
|
||||
arr[index] = num
|
||||
}
|
||||
|
||||
/* Direct traversal of list elements */
|
||||
func add(num: Int) {
|
||||
// When the number of elements exceeds capacity, trigger the extension mechanism
|
||||
if size() == capacity() {
|
||||
extendCapacity()
|
||||
}
|
||||
arr[size()] = num
|
||||
// Update the number of elements
|
||||
_size += 1
|
||||
}
|
||||
|
||||
/* Sort list */
|
||||
func insert(index: Int, num: Int) {
|
||||
if index < 0 || index >= size() {
|
||||
fatalError("Index out of bounds")
|
||||
}
|
||||
// When the number of elements exceeds capacity, trigger the extension mechanism
|
||||
if size() == capacity() {
|
||||
extendCapacity()
|
||||
}
|
||||
// Move all elements after index index forward by one position
|
||||
for j in (index ..< size()).reversed() {
|
||||
arr[j + 1] = arr[j]
|
||||
}
|
||||
arr[index] = num
|
||||
// Update the number of elements
|
||||
_size += 1
|
||||
}
|
||||
|
||||
/* Remove element */
|
||||
@discardableResult
|
||||
func remove(index: Int) -> Int {
|
||||
if index < 0 || index >= size() {
|
||||
fatalError("Index out of bounds")
|
||||
}
|
||||
let num = arr[index]
|
||||
// Move all elements after index forward by one position
|
||||
for j in index ..< (size() - 1) {
|
||||
arr[j] = arr[j + 1]
|
||||
}
|
||||
// Update the number of elements
|
||||
_size -= 1
|
||||
// Return the removed element
|
||||
return num
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
func extendCapacity() {
|
||||
// Create a new array with length extendRatio times the original array and copy the original array to the new array
|
||||
arr = arr + Array(repeating: 0, count: capacity() * (extendRatio - 1))
|
||||
// Add elements at the end
|
||||
_capacity = arr.count
|
||||
}
|
||||
|
||||
/* Convert list to array */
|
||||
func toArray() -> [Int] {
|
||||
Array(arr.prefix(size()))
|
||||
}
|
||||
}
|
||||
|
||||
@main
|
||||
enum _MyList {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
/* Initialize list */
|
||||
let nums = MyList()
|
||||
/* Direct traversal of list elements */
|
||||
nums.add(num: 1)
|
||||
nums.add(num: 3)
|
||||
nums.add(num: 2)
|
||||
nums.add(num: 5)
|
||||
nums.add(num: 4)
|
||||
print("List nums = \(nums.toArray()), capacity = \(nums.capacity()), length = \(nums.size())")
|
||||
|
||||
/* Sort list */
|
||||
nums.insert(index: 3, num: 6)
|
||||
print("Insert number 6 at index 3, get nums = \(nums.toArray())")
|
||||
|
||||
/* Remove element */
|
||||
nums.remove(index: 3)
|
||||
print("Delete element at index 3, get nums = \(nums.toArray())")
|
||||
|
||||
/* Update element */
|
||||
let num = nums.get(index: 1)
|
||||
print("Access element at index 1, get num = \(num)")
|
||||
|
||||
/* Add elements at the end */
|
||||
nums.set(index: 1, num: 0)
|
||||
print("Update element at index 1 to 0, get nums = \(nums.toArray())")
|
||||
|
||||
/* Test capacity expansion mechanism */
|
||||
for i in 0 ..< 10 {
|
||||
// At i = 5, the list length will exceed the list capacity, triggering the expansion mechanism
|
||||
nums.add(num: i)
|
||||
}
|
||||
print("After expansion, list nums = \(nums.toArray()), capacity = \(nums.capacity()), length = \(nums.size())")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* File: n_queens.swift
|
||||
* Created Time: 2023-05-14
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Backtracking algorithm: N queens */
|
||||
func backtrack(row: Int, n: Int, state: inout [[String]], res: inout [[[String]]], cols: inout [Bool], diags1: inout [Bool], diags2: inout [Bool]) {
|
||||
// When all rows are placed, record the solution
|
||||
if row == n {
|
||||
res.append(state)
|
||||
return
|
||||
}
|
||||
// Traverse all columns
|
||||
for col in 0 ..< n {
|
||||
// Calculate the main diagonal and anti-diagonal corresponding to this cell
|
||||
let diag1 = row - col + n - 1
|
||||
let diag2 = row + col
|
||||
// Pruning: do not allow queens to exist in the column, main diagonal, and anti-diagonal of this cell
|
||||
if !cols[col] && !diags1[diag1] && !diags2[diag2] {
|
||||
// Attempt: place the queen in this cell
|
||||
state[row][col] = "Q"
|
||||
cols[col] = true
|
||||
diags1[diag1] = true
|
||||
diags2[diag2] = true
|
||||
// Place the next row
|
||||
backtrack(row: row + 1, n: n, state: &state, res: &res, cols: &cols, diags1: &diags1, diags2: &diags2)
|
||||
// Backtrack: restore this cell to an empty cell
|
||||
state[row][col] = "#"
|
||||
cols[col] = false
|
||||
diags1[diag1] = false
|
||||
diags2[diag2] = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Solve N queens */
|
||||
func nQueens(n: Int) -> [[[String]]] {
|
||||
// Initialize an n*n chessboard, where 'Q' represents a queen and '#' represents an empty cell
|
||||
var state = Array(repeating: Array(repeating: "#", count: n), count: n)
|
||||
var cols = Array(repeating: false, count: n) // Record whether there is a queen in the column
|
||||
var diags1 = Array(repeating: false, count: 2 * n - 1) // Record whether there is a queen on the main diagonal
|
||||
var diags2 = Array(repeating: false, count: 2 * n - 1) // Record whether there is a queen on the anti-diagonal
|
||||
var res: [[[String]]] = []
|
||||
|
||||
backtrack(row: 0, n: n, state: &state, res: &res, cols: &cols, diags1: &diags1, diags2: &diags2)
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
@main
|
||||
enum NQueens {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let n = 4
|
||||
let res = nQueens(n: n)
|
||||
|
||||
print("Input board size is \(n)")
|
||||
print("Total queen placement solutions: \(res.count)")
|
||||
for state in res {
|
||||
print("--------------------")
|
||||
for row in state {
|
||||
print(row)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* File: permutations_i.swift
|
||||
* Created Time: 2023-04-30
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Backtracking algorithm: Permutations I */
|
||||
func backtrack(state: inout [Int], choices: [Int], selected: inout [Bool], res: inout [[Int]]) {
|
||||
// When the state length equals the number of elements, record the solution
|
||||
if state.count == choices.count {
|
||||
res.append(state)
|
||||
return
|
||||
}
|
||||
// Traverse all choices
|
||||
for (i, choice) in choices.enumerated() {
|
||||
// Pruning: do not allow repeated selection of elements
|
||||
if !selected[i] {
|
||||
// Attempt: make choice, update state
|
||||
selected[i] = true
|
||||
state.append(choice)
|
||||
// Proceed to the next round of selection
|
||||
backtrack(state: &state, choices: choices, selected: &selected, res: &res)
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
selected[i] = false
|
||||
state.removeLast()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Permutations I */
|
||||
func permutationsI(nums: [Int]) -> [[Int]] {
|
||||
var state: [Int] = []
|
||||
var selected = Array(repeating: false, count: nums.count)
|
||||
var res: [[Int]] = []
|
||||
backtrack(state: &state, choices: nums, selected: &selected, res: &res)
|
||||
return res
|
||||
}
|
||||
|
||||
@main
|
||||
enum PermutationsI {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let nums = [1, 2, 3]
|
||||
|
||||
let res = permutationsI(nums: nums)
|
||||
|
||||
print("Input array nums = \(nums)")
|
||||
print("All permutations res = \(res)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* File: permutations_ii.swift
|
||||
* Created Time: 2023-04-30
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Backtracking algorithm: Permutations II */
|
||||
func backtrack(state: inout [Int], choices: [Int], selected: inout [Bool], res: inout [[Int]]) {
|
||||
// When the state length equals the number of elements, record the solution
|
||||
if state.count == choices.count {
|
||||
res.append(state)
|
||||
return
|
||||
}
|
||||
// Traverse all choices
|
||||
var duplicated: Set<Int> = []
|
||||
for (i, choice) in choices.enumerated() {
|
||||
// Pruning: do not allow repeated selection of elements and do not allow repeated selection of equal elements
|
||||
if !selected[i], !duplicated.contains(choice) {
|
||||
// Attempt: make choice, update state
|
||||
duplicated.insert(choice) // Record the selected element value
|
||||
selected[i] = true
|
||||
state.append(choice)
|
||||
// Proceed to the next round of selection
|
||||
backtrack(state: &state, choices: choices, selected: &selected, res: &res)
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
selected[i] = false
|
||||
state.removeLast()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Permutations II */
|
||||
func permutationsII(nums: [Int]) -> [[Int]] {
|
||||
var state: [Int] = []
|
||||
var selected = Array(repeating: false, count: nums.count)
|
||||
var res: [[Int]] = []
|
||||
backtrack(state: &state, choices: nums, selected: &selected, res: &res)
|
||||
return res
|
||||
}
|
||||
|
||||
@main
|
||||
enum PermutationsII {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let nums = [1, 2, 3]
|
||||
|
||||
let res = permutationsII(nums: nums)
|
||||
|
||||
print("Input array nums = \(nums)")
|
||||
print("All permutations res = \(res)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* File: preorder_traversal_i_compact.swift
|
||||
* Created Time: 2023-04-30
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
import utils
|
||||
|
||||
var res: [TreeNode] = []
|
||||
|
||||
/* Preorder traversal: Example 1 */
|
||||
func preOrder(root: TreeNode?) {
|
||||
guard let root = root else {
|
||||
return
|
||||
}
|
||||
if root.val == 7 {
|
||||
// Record solution
|
||||
res.append(root)
|
||||
}
|
||||
preOrder(root: root.left)
|
||||
preOrder(root: root.right)
|
||||
}
|
||||
|
||||
@main
|
||||
enum PreorderTraversalICompact {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let root = TreeNode.listToTree(arr: [1, 7, 3, 4, 5, 6, 7])
|
||||
print("\nInitialize binary tree")
|
||||
PrintUtil.printTree(root: root)
|
||||
|
||||
// Preorder traversal
|
||||
res = []
|
||||
preOrder(root: root)
|
||||
|
||||
print("\nOutput all nodes with value 7")
|
||||
var vals: [Int] = []
|
||||
for node in res {
|
||||
vals.append(node.val)
|
||||
}
|
||||
print(vals)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* File: preorder_traversal_ii_compact.swift
|
||||
* Created Time: 2023-04-30
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
import utils
|
||||
|
||||
var path: [TreeNode] = []
|
||||
var res: [[TreeNode]] = []
|
||||
|
||||
/* Preorder traversal: Example 2 */
|
||||
func preOrder(root: TreeNode?) {
|
||||
guard let root = root else {
|
||||
return
|
||||
}
|
||||
// Attempt
|
||||
path.append(root)
|
||||
if root.val == 7 {
|
||||
// Record solution
|
||||
res.append(path)
|
||||
}
|
||||
preOrder(root: root.left)
|
||||
preOrder(root: root.right)
|
||||
// Backtrack
|
||||
path.removeLast()
|
||||
}
|
||||
|
||||
@main
|
||||
enum PreorderTraversalIICompact {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let root = TreeNode.listToTree(arr: [1, 7, 3, 4, 5, 6, 7])
|
||||
print("\nInitialize binary tree")
|
||||
PrintUtil.printTree(root: root)
|
||||
|
||||
// Preorder traversal
|
||||
path = []
|
||||
res = []
|
||||
preOrder(root: root)
|
||||
|
||||
print("\nOutput all paths from root node to node 7")
|
||||
for path in res {
|
||||
var vals: [Int] = []
|
||||
for node in path {
|
||||
vals.append(node.val)
|
||||
}
|
||||
print(vals)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* File: preorder_traversal_iii_compact.swift
|
||||
* Created Time: 2023-04-30
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
import utils
|
||||
|
||||
var path: [TreeNode] = []
|
||||
var res: [[TreeNode]] = []
|
||||
|
||||
/* Preorder traversal: Example 3 */
|
||||
func preOrder(root: TreeNode?) {
|
||||
// Pruning
|
||||
guard let root = root, root.val != 3 else {
|
||||
return
|
||||
}
|
||||
// Attempt
|
||||
path.append(root)
|
||||
if root.val == 7 {
|
||||
// Record solution
|
||||
res.append(path)
|
||||
}
|
||||
preOrder(root: root.left)
|
||||
preOrder(root: root.right)
|
||||
// Backtrack
|
||||
path.removeLast()
|
||||
}
|
||||
|
||||
@main
|
||||
enum PreorderTraversalIIICompact {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let root = TreeNode.listToTree(arr: [1, 7, 3, 4, 5, 6, 7])
|
||||
print("\nInitialize binary tree")
|
||||
PrintUtil.printTree(root: root)
|
||||
|
||||
// Preorder traversal
|
||||
path = []
|
||||
res = []
|
||||
preOrder(root: root)
|
||||
|
||||
print("\nOutput all paths from root node to node 7, paths do not include nodes with value 3")
|
||||
for path in res {
|
||||
var vals: [Int] = []
|
||||
for node in path {
|
||||
vals.append(node.val)
|
||||
}
|
||||
print(vals)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* File: preorder_traversal_iii_template.swift
|
||||
* Created Time: 2023-04-30
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
import utils
|
||||
|
||||
/* Check if the current state is a solution */
|
||||
func isSolution(state: [TreeNode]) -> Bool {
|
||||
!state.isEmpty && state.last!.val == 7
|
||||
}
|
||||
|
||||
/* Record solution */
|
||||
func recordSolution(state: [TreeNode], res: inout [[TreeNode]]) {
|
||||
res.append(state)
|
||||
}
|
||||
|
||||
/* Check if the choice is valid under the current state */
|
||||
func isValid(state: [TreeNode], choice: TreeNode?) -> Bool {
|
||||
choice != nil && choice!.val != 3
|
||||
}
|
||||
|
||||
/* Update state */
|
||||
func makeChoice(state: inout [TreeNode], choice: TreeNode) {
|
||||
state.append(choice)
|
||||
}
|
||||
|
||||
/* Restore state */
|
||||
func undoChoice(state: inout [TreeNode], choice: TreeNode) {
|
||||
state.removeLast()
|
||||
}
|
||||
|
||||
/* Backtracking algorithm: Example 3 */
|
||||
func backtrack(state: inout [TreeNode], choices: [TreeNode], res: inout [[TreeNode]]) {
|
||||
// Check if it is a solution
|
||||
if isSolution(state: state) {
|
||||
recordSolution(state: state, res: &res)
|
||||
}
|
||||
// Traverse all choices
|
||||
for choice in choices {
|
||||
// Pruning: check if the choice is valid
|
||||
if isValid(state: state, choice: choice) {
|
||||
// Attempt: make choice, update state
|
||||
makeChoice(state: &state, choice: choice)
|
||||
// Proceed to the next round of selection
|
||||
backtrack(state: &state, choices: [choice.left, choice.right].compactMap { $0 }, res: &res)
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
undoChoice(state: &state, choice: choice)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@main
|
||||
enum PreorderTraversalIIITemplate {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let root = TreeNode.listToTree(arr: [1, 7, 3, 4, 5, 6, 7])
|
||||
print("\nInitialize binary tree")
|
||||
PrintUtil.printTree(root: root)
|
||||
|
||||
// Backtracking algorithm
|
||||
var state: [TreeNode] = []
|
||||
var res: [[TreeNode]] = []
|
||||
backtrack(state: &state, choices: [root].compactMap { $0 }, res: &res)
|
||||
|
||||
print("\nOutput all paths from root node to node 7, paths do not include nodes with value 3")
|
||||
for path in res {
|
||||
var vals: [Int] = []
|
||||
for node in path {
|
||||
vals.append(node.val)
|
||||
}
|
||||
print(vals)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* File: subset_sum_i.swift
|
||||
* Created Time: 2023-07-02
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Backtracking algorithm: Subset sum I */
|
||||
func backtrack(state: inout [Int], target: Int, choices: [Int], start: Int, res: inout [[Int]]) {
|
||||
// When the subset sum equals target, record the solution
|
||||
if target == 0 {
|
||||
res.append(state)
|
||||
return
|
||||
}
|
||||
// Traverse all choices
|
||||
// Pruning 2: start traversing from start to avoid generating duplicate subsets
|
||||
for i in choices.indices.dropFirst(start) {
|
||||
// Pruning 1: if the subset sum exceeds target, end the loop directly
|
||||
// This is because the array is sorted, and later elements are larger, so the subset sum will definitely exceed target
|
||||
if target - choices[i] < 0 {
|
||||
break
|
||||
}
|
||||
// Attempt: make choice, update target, start
|
||||
state.append(choices[i])
|
||||
// Proceed to the next round of selection
|
||||
backtrack(state: &state, target: target - choices[i], choices: choices, start: i, res: &res)
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
state.removeLast()
|
||||
}
|
||||
}
|
||||
|
||||
/* Solve subset sum I */
|
||||
func subsetSumI(nums: [Int], target: Int) -> [[Int]] {
|
||||
var state: [Int] = [] // State (subset)
|
||||
let nums = nums.sorted() // Sort nums
|
||||
let start = 0 // Start point for traversal
|
||||
var res: [[Int]] = [] // Result list (subset list)
|
||||
backtrack(state: &state, target: target, choices: nums, start: start, res: &res)
|
||||
return res
|
||||
}
|
||||
|
||||
@main
|
||||
enum SubsetSumI {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let nums = [3, 4, 5]
|
||||
let target = 9
|
||||
|
||||
let res = subsetSumI(nums: nums, target: target)
|
||||
|
||||
print("Input array nums = \(nums), target = \(target)")
|
||||
print("All subsets with sum equal to \(target) res = \(res)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* File: subset_sum_i_naive.swift
|
||||
* Created Time: 2023-07-02
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Backtracking algorithm: Subset sum I */
|
||||
func backtrack(state: inout [Int], target: Int, total: Int, choices: [Int], res: inout [[Int]]) {
|
||||
// When the subset sum equals target, record the solution
|
||||
if total == target {
|
||||
res.append(state)
|
||||
return
|
||||
}
|
||||
// Traverse all choices
|
||||
for i in choices.indices {
|
||||
// Pruning: if the subset sum exceeds target, skip this choice
|
||||
if total + choices[i] > target {
|
||||
continue
|
||||
}
|
||||
// Attempt: make choice, update element sum total
|
||||
state.append(choices[i])
|
||||
// Proceed to the next round of selection
|
||||
backtrack(state: &state, target: target, total: total + choices[i], choices: choices, res: &res)
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
state.removeLast()
|
||||
}
|
||||
}
|
||||
|
||||
/* Solve subset sum I (including duplicate subsets) */
|
||||
func subsetSumINaive(nums: [Int], target: Int) -> [[Int]] {
|
||||
var state: [Int] = [] // State (subset)
|
||||
let total = 0 // Subset sum
|
||||
var res: [[Int]] = [] // Result list (subset list)
|
||||
backtrack(state: &state, target: target, total: total, choices: nums, res: &res)
|
||||
return res
|
||||
}
|
||||
|
||||
@main
|
||||
enum SubsetSumINaive {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let nums = [3, 4, 5]
|
||||
let target = 9
|
||||
|
||||
let res = subsetSumINaive(nums: nums, target: target)
|
||||
|
||||
print("Input array nums = \(nums), target = \(target)")
|
||||
print("All subsets with sum equal to \(target) res = \(res)")
|
||||
print("Please note that this method outputs results containing duplicate sets")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* File: subset_sum_ii.swift
|
||||
* Created Time: 2023-07-02
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Backtracking algorithm: Subset sum II */
|
||||
func backtrack(state: inout [Int], target: Int, choices: [Int], start: Int, res: inout [[Int]]) {
|
||||
// When the subset sum equals target, record the solution
|
||||
if target == 0 {
|
||||
res.append(state)
|
||||
return
|
||||
}
|
||||
// Traverse all choices
|
||||
// Pruning 2: start traversing from start to avoid generating duplicate subsets
|
||||
// Pruning 3: start traversing from start to avoid repeatedly selecting the same element
|
||||
for i in choices.indices.dropFirst(start) {
|
||||
// Pruning 1: if the subset sum exceeds target, end the loop directly
|
||||
// This is because the array is sorted, and later elements are larger, so the subset sum will definitely exceed target
|
||||
if target - choices[i] < 0 {
|
||||
break
|
||||
}
|
||||
// Pruning 4: if this element equals the left element, it means this search branch is duplicate, skip it directly
|
||||
if i > start, choices[i] == choices[i - 1] {
|
||||
continue
|
||||
}
|
||||
// Attempt: make choice, update target, start
|
||||
state.append(choices[i])
|
||||
// Proceed to the next round of selection
|
||||
backtrack(state: &state, target: target - choices[i], choices: choices, start: i + 1, res: &res)
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
state.removeLast()
|
||||
}
|
||||
}
|
||||
|
||||
/* Solve subset sum II */
|
||||
func subsetSumII(nums: [Int], target: Int) -> [[Int]] {
|
||||
var state: [Int] = [] // State (subset)
|
||||
let nums = nums.sorted() // Sort nums
|
||||
let start = 0 // Start point for traversal
|
||||
var res: [[Int]] = [] // Result list (subset list)
|
||||
backtrack(state: &state, target: target, choices: nums, start: start, res: &res)
|
||||
return res
|
||||
}
|
||||
|
||||
@main
|
||||
enum SubsetSumII {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let nums = [4, 4, 5]
|
||||
let target = 9
|
||||
|
||||
let res = subsetSumII(nums: nums, target: target)
|
||||
|
||||
print("Input array nums = \(nums), target = \(target)")
|
||||
print("All subsets with sum equal to \(target) res = \(res)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* File: iteration.swift
|
||||
* Created Time: 2023-09-02
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* for loop */
|
||||
func forLoop(n: Int) -> Int {
|
||||
var res = 0
|
||||
// Sum 1, 2, ..., n-1, n
|
||||
for i in 1 ... n {
|
||||
res += i
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
/* while loop */
|
||||
func whileLoop(n: Int) -> Int {
|
||||
var res = 0
|
||||
var i = 1 // Initialize condition variable
|
||||
// Sum 1, 2, ..., n-1, n
|
||||
while i <= n {
|
||||
res += i
|
||||
i += 1 // Update condition variable
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
/* while loop (two updates) */
|
||||
func whileLoopII(n: Int) -> Int {
|
||||
var res = 0
|
||||
var i = 1 // Initialize condition variable
|
||||
// Sum 1, 4, 10, ...
|
||||
while i <= n {
|
||||
res += i
|
||||
// Update condition variable
|
||||
i += 1
|
||||
i *= 2
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
/* Nested for loop */
|
||||
func nestedForLoop(n: Int) -> String {
|
||||
var res = ""
|
||||
// Loop i = 1, 2, ..., n-1, n
|
||||
for i in 1 ... n {
|
||||
// Loop j = 1, 2, ..., n-1, n
|
||||
for j in 1 ... n {
|
||||
res.append("(\(i), \(j)), ")
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
@main
|
||||
enum Iteration {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let n = 5
|
||||
var res = 0
|
||||
|
||||
res = forLoop(n: n)
|
||||
print("\nFor loop sum result res = \(res)")
|
||||
|
||||
res = whileLoop(n: n)
|
||||
print("\nWhile loop sum result res = \(res)")
|
||||
|
||||
res = whileLoopII(n: n)
|
||||
print("\nWhile loop (two updates) sum result res = \(res)")
|
||||
|
||||
let resStr = nestedForLoop(n: n)
|
||||
print("\nNested for loop traversal result \(resStr)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* File: recursion.swift
|
||||
* Created Time: 2023-09-02
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Recursion */
|
||||
func recur(n: Int) -> Int {
|
||||
// Termination condition
|
||||
if n == 1 {
|
||||
return 1
|
||||
}
|
||||
// Recurse: recursive call
|
||||
let res = recur(n: n - 1)
|
||||
// Return: return result
|
||||
return n + res
|
||||
}
|
||||
|
||||
/* Simulate recursion using iteration */
|
||||
func forLoopRecur(n: Int) -> Int {
|
||||
// Use an explicit stack to simulate the system call stack
|
||||
var stack: [Int] = []
|
||||
var res = 0
|
||||
// Recurse: recursive call
|
||||
for i in (1 ... n).reversed() {
|
||||
// Simulate "recurse" with "push"
|
||||
stack.append(i)
|
||||
}
|
||||
// Return: return result
|
||||
while !stack.isEmpty {
|
||||
// Simulate "return" with "pop"
|
||||
res += stack.removeLast()
|
||||
}
|
||||
// res = 1+2+3+...+n
|
||||
return res
|
||||
}
|
||||
|
||||
/* Tail recursion */
|
||||
func tailRecur(n: Int, res: Int) -> Int {
|
||||
// Termination condition
|
||||
if n == 0 {
|
||||
return res
|
||||
}
|
||||
// Tail recursive call
|
||||
return tailRecur(n: n - 1, res: res + n)
|
||||
}
|
||||
|
||||
/* Fibonacci sequence: recursion */
|
||||
func fib(n: Int) -> Int {
|
||||
// Termination condition f(1) = 0, f(2) = 1
|
||||
if n == 1 || n == 2 {
|
||||
return n - 1
|
||||
}
|
||||
// Recursive call f(n) = f(n-1) + f(n-2)
|
||||
let res = fib(n: n - 1) + fib(n: n - 2)
|
||||
// Return result f(n)
|
||||
return res
|
||||
}
|
||||
|
||||
@main
|
||||
enum Recursion {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let n = 5
|
||||
var res = 0
|
||||
|
||||
res = recursion.recur(n: n)
|
||||
print("\nRecursion sum result res = \(res)")
|
||||
|
||||
res = recursion.forLoopRecur(n: n)
|
||||
print("\nUsing iteration to simulate recursion sum result res = \(res)")
|
||||
|
||||
res = recursion.tailRecur(n: n, res: 0)
|
||||
print("\nTail recursion sum result res = \(res)")
|
||||
|
||||
res = recursion.fib(n: n)
|
||||
print("\nThe \(n)th Fibonacci number is \(res)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* File: space_complexity.swift
|
||||
* Created Time: 2023-01-01
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
import utils
|
||||
|
||||
/* Function */
|
||||
@discardableResult
|
||||
func function() -> Int {
|
||||
// Perform some operations
|
||||
return 0
|
||||
}
|
||||
|
||||
/* Constant order */
|
||||
func constant(n: Int) {
|
||||
// Constants, variables, objects occupy O(1) space
|
||||
let a = 0
|
||||
var b = 0
|
||||
let nums = Array(repeating: 0, count: 10000)
|
||||
let node = ListNode(x: 0)
|
||||
// Variables in the loop occupy O(1) space
|
||||
for _ in 0 ..< n {
|
||||
let c = 0
|
||||
}
|
||||
// Functions in the loop occupy O(1) space
|
||||
for _ in 0 ..< n {
|
||||
function()
|
||||
}
|
||||
}
|
||||
|
||||
/* Linear order */
|
||||
func linear(n: Int) {
|
||||
// Array of length n uses O(n) space
|
||||
let nums = Array(repeating: 0, count: n)
|
||||
// A list of length n occupies O(n) space
|
||||
let nodes = (0 ..< n).map { ListNode(x: $0) }
|
||||
// A hash table of length n occupies O(n) space
|
||||
let map = Dictionary(uniqueKeysWithValues: (0 ..< n).map { ($0, "\($0)") })
|
||||
}
|
||||
|
||||
/* Linear order (recursive implementation) */
|
||||
func linearRecur(n: Int) {
|
||||
print("Recursion n = \(n)")
|
||||
if n == 1 {
|
||||
return
|
||||
}
|
||||
linearRecur(n: n - 1)
|
||||
}
|
||||
|
||||
/* Exponential order */
|
||||
func quadratic(n: Int) {
|
||||
// 2D list uses O(n^2) space
|
||||
let numList = Array(repeating: Array(repeating: 0, count: n), count: n)
|
||||
}
|
||||
|
||||
/* Quadratic order (recursive implementation) */
|
||||
@discardableResult
|
||||
func quadraticRecur(n: Int) -> Int {
|
||||
if n <= 0 {
|
||||
return 0
|
||||
}
|
||||
// Array nums has length n, n-1, ..., 2, 1
|
||||
let nums = Array(repeating: 0, count: n)
|
||||
print("In recursion n = \(n), nums length = \(nums.count)")
|
||||
return quadraticRecur(n: n - 1)
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
func buildTree(n: Int) -> TreeNode? {
|
||||
if n == 0 {
|
||||
return nil
|
||||
}
|
||||
let root = TreeNode(x: 0)
|
||||
root.left = buildTree(n: n - 1)
|
||||
root.right = buildTree(n: n - 1)
|
||||
return root
|
||||
}
|
||||
|
||||
@main
|
||||
enum SpaceComplexity {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let n = 5
|
||||
// Constant order
|
||||
constant(n: n)
|
||||
// Linear order
|
||||
linear(n: n)
|
||||
linearRecur(n: n)
|
||||
// Exponential order
|
||||
quadratic(n: n)
|
||||
quadraticRecur(n: n)
|
||||
// Exponential order
|
||||
let root = buildTree(n: n)
|
||||
PrintUtil.printTree(root: root)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
/**
|
||||
* File: time_complexity.swift
|
||||
* Created Time: 2022-12-26
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Constant order */
|
||||
func constant(n: Int) -> Int {
|
||||
var count = 0
|
||||
let size = 100_000
|
||||
for _ in 0 ..< size {
|
||||
count += 1
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
/* Linear order */
|
||||
func linear(n: Int) -> Int {
|
||||
var count = 0
|
||||
for _ in 0 ..< n {
|
||||
count += 1
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
/* Linear order (traversing array) */
|
||||
func arrayTraversal(nums: [Int]) -> Int {
|
||||
var count = 0
|
||||
// Number of iterations is proportional to the array length
|
||||
for _ in nums {
|
||||
count += 1
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
/* Exponential order */
|
||||
func quadratic(n: Int) -> Int {
|
||||
var count = 0
|
||||
// Number of iterations is quadratically related to the data size n
|
||||
for _ in 0 ..< n {
|
||||
for _ in 0 ..< n {
|
||||
count += 1
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
/* Quadratic order (bubble sort) */
|
||||
func bubbleSort(nums: inout [Int]) -> Int {
|
||||
var count = 0 // Counter
|
||||
// Outer loop: unsorted range is [0, i]
|
||||
for i in nums.indices.dropFirst().reversed() {
|
||||
// Inner loop: swap the largest element in the unsorted range [0, i] to the rightmost end of that range
|
||||
for j in 0 ..< i {
|
||||
if nums[j] > nums[j + 1] {
|
||||
// Swap nums[j] and nums[j + 1]
|
||||
let tmp = nums[j]
|
||||
nums[j] = nums[j + 1]
|
||||
nums[j + 1] = tmp
|
||||
count += 3 // Element swap includes 3 unit operations
|
||||
}
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
/* Exponential order (loop implementation) */
|
||||
func exponential(n: Int) -> Int {
|
||||
var count = 0
|
||||
var base = 1
|
||||
// Cells divide into two every round, forming sequence 1, 2, 4, 8, ..., 2^(n-1)
|
||||
for _ in 0 ..< n {
|
||||
for _ in 0 ..< base {
|
||||
count += 1
|
||||
}
|
||||
base *= 2
|
||||
}
|
||||
// count = 1 + 2 + 4 + 8 + .. + 2^(n-1) = 2^n - 1
|
||||
return count
|
||||
}
|
||||
|
||||
/* Exponential order (recursive implementation) */
|
||||
func expRecur(n: Int) -> Int {
|
||||
if n == 1 {
|
||||
return 1
|
||||
}
|
||||
return expRecur(n: n - 1) + expRecur(n: n - 1) + 1
|
||||
}
|
||||
|
||||
/* Logarithmic order (loop implementation) */
|
||||
func logarithmic(n: Int) -> Int {
|
||||
var count = 0
|
||||
var n = n
|
||||
while n > 1 {
|
||||
n = n / 2
|
||||
count += 1
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
/* Logarithmic order (recursive implementation) */
|
||||
func logRecur(n: Int) -> Int {
|
||||
if n <= 1 {
|
||||
return 0
|
||||
}
|
||||
return logRecur(n: n / 2) + 1
|
||||
}
|
||||
|
||||
/* Linearithmic order */
|
||||
func linearLogRecur(n: Int) -> Int {
|
||||
if n <= 1 {
|
||||
return 1
|
||||
}
|
||||
var count = linearLogRecur(n: n / 2) + linearLogRecur(n: n / 2)
|
||||
for _ in stride(from: 0, to: n, by: 1) {
|
||||
count += 1
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
/* Factorial order (recursive implementation) */
|
||||
func factorialRecur(n: Int) -> Int {
|
||||
if n == 0 {
|
||||
return 1
|
||||
}
|
||||
var count = 0
|
||||
// Split from 1 into n
|
||||
for _ in 0 ..< n {
|
||||
count += factorialRecur(n: n - 1)
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
@main
|
||||
enum TimeComplexity {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
// You can modify n to run and observe the trend of the number of operations for various complexities
|
||||
let n = 8
|
||||
print("Input data size n = \(n)")
|
||||
|
||||
var count = constant(n: n)
|
||||
print("Constant-time operations count = \(count)")
|
||||
|
||||
count = linear(n: n)
|
||||
print("Linear-time operations count = \(count)")
|
||||
count = arrayTraversal(nums: Array(repeating: 0, count: n))
|
||||
print("Linear-time (array traversal) operations count = \(count)")
|
||||
|
||||
count = quadratic(n: n)
|
||||
print("Quadratic-time operations count = \(count)")
|
||||
var nums = Array(stride(from: n, to: 0, by: -1)) // [n,n-1,...,2,1]
|
||||
count = bubbleSort(nums: &nums)
|
||||
print("Quadratic-time (bubble sort) operations count = \(count)")
|
||||
|
||||
count = exponential(n: n)
|
||||
print("Exponential-time (iterative) operations count = \(count)")
|
||||
count = expRecur(n: n)
|
||||
print("Exponential-time (recursive) operations count = \(count)")
|
||||
|
||||
count = logarithmic(n: n)
|
||||
print("Logarithmic-time (iterative) operations count = \(count)")
|
||||
count = logRecur(n: n)
|
||||
print("Logarithmic-time (recursive) operations count = \(count)")
|
||||
|
||||
count = linearLogRecur(n: n)
|
||||
print("Linearithmic-time (recursive) operations count = \(count)")
|
||||
|
||||
count = factorialRecur(n: n)
|
||||
print("Factorial-time (recursive) operations count = \(count)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* File: worst_best_time_complexity.swift
|
||||
* Created Time: 2022-12-26
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Generate an array with elements { 1, 2, ..., n }, order shuffled */
|
||||
func randomNumbers(n: Int) -> [Int] {
|
||||
// Generate array nums = { 1, 2, 3, ..., n }
|
||||
var nums = Array(1 ... n)
|
||||
// Randomly shuffle array elements
|
||||
nums.shuffle()
|
||||
return nums
|
||||
}
|
||||
|
||||
/* Find the index of number 1 in array nums */
|
||||
func findOne(nums: [Int]) -> Int {
|
||||
for i in nums.indices {
|
||||
// When element 1 is at the head of the array, best time complexity O(1) is achieved
|
||||
// When element 1 is at the tail of the array, worst time complexity O(n) is achieved
|
||||
if nums[i] == 1 {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
@main
|
||||
enum WorstBestTimeComplexity {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
for _ in 0 ..< 10 {
|
||||
let n = 100
|
||||
let nums = randomNumbers(n: n)
|
||||
let index = findOne(nums: nums)
|
||||
print("Array [ 1, 2, ..., n ] after shuffling = \(nums)")
|
||||
print("Index of number 1 is \(index)")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* File: binary_search_recur.swift
|
||||
* Created Time: 2023-09-02
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Binary search: problem f(i, j) */
|
||||
func dfs(nums: [Int], target: Int, i: Int, j: Int) -> Int {
|
||||
// If the interval is empty, it means there is no target element, return -1
|
||||
if i > j {
|
||||
return -1
|
||||
}
|
||||
// Calculate the midpoint index m
|
||||
let m = (i + j) / 2
|
||||
if nums[m] < target {
|
||||
// Recursion subproblem f(m+1, j)
|
||||
return dfs(nums: nums, target: target, i: m + 1, j: j)
|
||||
} else if nums[m] > target {
|
||||
// Recursion subproblem f(i, m-1)
|
||||
return dfs(nums: nums, target: target, i: i, j: m - 1)
|
||||
} else {
|
||||
// Found the target element, return its index
|
||||
return m
|
||||
}
|
||||
}
|
||||
|
||||
/* Binary search */
|
||||
func binarySearch(nums: [Int], target: Int) -> Int {
|
||||
// Solve the problem f(0, n-1)
|
||||
dfs(nums: nums, target: target, i: nums.startIndex, j: nums.endIndex - 1)
|
||||
}
|
||||
|
||||
@main
|
||||
enum BinarySearchRecur {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let target = 6
|
||||
let nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35]
|
||||
|
||||
// Binary search (closed interval on both sides)
|
||||
let index = binarySearch(nums: nums, target: target)
|
||||
print("Index of target element 6 = \(index)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* File: build_tree.swift
|
||||
* Created Time: 2023-09-02
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
import utils
|
||||
|
||||
/* Build binary tree: divide and conquer */
|
||||
func dfs(preorder: [Int], inorderMap: [Int: Int], i: Int, l: Int, r: Int) -> TreeNode? {
|
||||
// Terminate when the subtree interval is empty
|
||||
if r - l < 0 {
|
||||
return nil
|
||||
}
|
||||
// Initialize the root node
|
||||
let root = TreeNode(x: preorder[i])
|
||||
// Query m to divide the left and right subtrees
|
||||
let m = inorderMap[preorder[i]]!
|
||||
// Subproblem: build the left subtree
|
||||
root.left = dfs(preorder: preorder, inorderMap: inorderMap, i: i + 1, l: l, r: m - 1)
|
||||
// Subproblem: build the right subtree
|
||||
root.right = dfs(preorder: preorder, inorderMap: inorderMap, i: i + 1 + m - l, l: m + 1, r: r)
|
||||
// Return the root node
|
||||
return root
|
||||
}
|
||||
|
||||
/* Build binary tree */
|
||||
func buildTree(preorder: [Int], inorder: [Int]) -> TreeNode? {
|
||||
// Initialize hash map, storing the mapping from inorder elements to indices
|
||||
let inorderMap = inorder.enumerated().reduce(into: [:]) { $0[$1.element] = $1.offset }
|
||||
return dfs(preorder: preorder, inorderMap: inorderMap, i: inorder.startIndex, l: inorder.startIndex, r: inorder.endIndex - 1)
|
||||
}
|
||||
|
||||
@main
|
||||
enum BuildTree {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let preorder = [3, 9, 2, 1, 7]
|
||||
let inorder = [9, 3, 1, 2, 7]
|
||||
print("Pre-order traversal = \(preorder)")
|
||||
print("In-order traversal = \(inorder)")
|
||||
|
||||
let root = buildTree(preorder: preorder, inorder: inorder)
|
||||
print("The constructed binary tree is:")
|
||||
PrintUtil.printTree(root: root)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* File: hanota.swift
|
||||
* Created Time: 2023-09-02
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Move a disk */
|
||||
func move(src: inout [Int], tar: inout [Int]) {
|
||||
// Take out a disk from the top of src
|
||||
let pan = src.popLast()!
|
||||
// Place the disk on top of tar
|
||||
tar.append(pan)
|
||||
}
|
||||
|
||||
/* Solve the Tower of Hanoi problem f(i) */
|
||||
func dfs(i: Int, src: inout [Int], buf: inout [Int], tar: inout [Int]) {
|
||||
// If there is only one disk left in src, move it directly to tar
|
||||
if i == 1 {
|
||||
move(src: &src, tar: &tar)
|
||||
return
|
||||
}
|
||||
// Subproblem f(i-1): move the top i-1 disks from src to buf using tar
|
||||
dfs(i: i - 1, src: &src, buf: &tar, tar: &buf)
|
||||
// Subproblem f(1): move the remaining disk from src to tar
|
||||
move(src: &src, tar: &tar)
|
||||
// Subproblem f(i-1): move the top i-1 disks from buf to tar using src
|
||||
dfs(i: i - 1, src: &buf, buf: &src, tar: &tar)
|
||||
}
|
||||
|
||||
/* Solve the Tower of Hanoi problem */
|
||||
func solveHanota(A: inout [Int], B: inout [Int], C: inout [Int]) {
|
||||
let n = A.count
|
||||
// The tail of the list is the top of the rod
|
||||
// Move top n disks from src to C using B
|
||||
dfs(i: n, src: &A, buf: &B, tar: &C)
|
||||
}
|
||||
|
||||
@main
|
||||
enum Hanota {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
// The tail of the list is the top of the rod
|
||||
var A = [5, 4, 3, 2, 1]
|
||||
var B: [Int] = []
|
||||
var C: [Int] = []
|
||||
print("In initial state:")
|
||||
print("A = \(A)")
|
||||
print("B = \(B)")
|
||||
print("C = \(C)")
|
||||
|
||||
solveHanota(A: &A, B: &B, C: &C)
|
||||
|
||||
print("After disk movement is complete:")
|
||||
print("A = \(A)")
|
||||
print("B = \(B)")
|
||||
print("C = \(C)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* File: climbing_stairs_backtrack.swift
|
||||
* Created Time: 2023-07-15
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Backtracking */
|
||||
func backtrack(choices: [Int], state: Int, n: Int, res: inout [Int]) {
|
||||
// When climbing to the n-th stair, add 1 to the solution count
|
||||
if state == n {
|
||||
res[0] += 1
|
||||
}
|
||||
// Traverse all choices
|
||||
for choice in choices {
|
||||
// Pruning: not allowed to go beyond the n-th stair
|
||||
if state + choice > n {
|
||||
continue
|
||||
}
|
||||
// Attempt: make choice, update state
|
||||
backtrack(choices: choices, state: state + choice, n: n, res: &res)
|
||||
// Backtrack
|
||||
}
|
||||
}
|
||||
|
||||
/* Climbing stairs: Backtracking */
|
||||
func climbingStairsBacktrack(n: Int) -> Int {
|
||||
let choices = [1, 2] // Can choose to climb up 1 or 2 stairs
|
||||
let state = 0 // Start climbing from the 0-th stair
|
||||
var res: [Int] = []
|
||||
res.append(0) // Use res[0] to record the solution count
|
||||
backtrack(choices: choices, state: state, n: n, res: &res)
|
||||
return res[0]
|
||||
}
|
||||
|
||||
@main
|
||||
enum ClimbingStairsBacktrack {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let n = 9
|
||||
|
||||
let res = climbingStairsBacktrack(n: n)
|
||||
print("Climbing \(n) stairs has \(res) solutions")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* File: climbing_stairs_constraint_dp.swift
|
||||
* Created Time: 2023-07-15
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Climbing stairs with constraint: Dynamic programming */
|
||||
func climbingStairsConstraintDP(n: Int) -> Int {
|
||||
if n == 1 || n == 2 {
|
||||
return 1
|
||||
}
|
||||
// Initialize dp table, used to store solutions to subproblems
|
||||
var dp = Array(repeating: Array(repeating: 0, count: 3), count: n + 1)
|
||||
// Initial state: preset the solution to the smallest subproblem
|
||||
dp[1][1] = 1
|
||||
dp[1][2] = 0
|
||||
dp[2][1] = 0
|
||||
dp[2][2] = 1
|
||||
// State transition: gradually solve larger subproblems from smaller ones
|
||||
for i in 3 ... n {
|
||||
dp[i][1] = dp[i - 1][2]
|
||||
dp[i][2] = dp[i - 2][1] + dp[i - 2][2]
|
||||
}
|
||||
return dp[n][1] + dp[n][2]
|
||||
}
|
||||
|
||||
@main
|
||||
enum ClimbingStairsConstraintDP {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let n = 9
|
||||
|
||||
let res = climbingStairsConstraintDP(n: n)
|
||||
print("Climbing \(n) stairs has \(res) solutions")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* File: climbing_stairs_dfs.swift
|
||||
* Created Time: 2023-07-15
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Search */
|
||||
func dfs(i: Int) -> Int {
|
||||
// Known dp[1] and dp[2], return them
|
||||
if i == 1 || i == 2 {
|
||||
return i
|
||||
}
|
||||
// dp[i] = dp[i-1] + dp[i-2]
|
||||
let count = dfs(i: i - 1) + dfs(i: i - 2)
|
||||
return count
|
||||
}
|
||||
|
||||
/* Climbing stairs: Search */
|
||||
func climbingStairsDFS(n: Int) -> Int {
|
||||
dfs(i: n)
|
||||
}
|
||||
|
||||
@main
|
||||
enum ClimbingStairsDFS {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let n = 9
|
||||
|
||||
let res = climbingStairsDFS(n: n)
|
||||
print("Climbing \(n) stairs has \(res) solutions")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* File: climbing_stairs_dfs_mem.swift
|
||||
* Created Time: 2023-07-15
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Memoization search */
|
||||
func dfs(i: Int, mem: inout [Int]) -> Int {
|
||||
// Known dp[1] and dp[2], return them
|
||||
if i == 1 || i == 2 {
|
||||
return i
|
||||
}
|
||||
// If record dp[i] exists, return it directly
|
||||
if mem[i] != -1 {
|
||||
return mem[i]
|
||||
}
|
||||
// dp[i] = dp[i-1] + dp[i-2]
|
||||
let count = dfs(i: i - 1, mem: &mem) + dfs(i: i - 2, mem: &mem)
|
||||
// Record dp[i]
|
||||
mem[i] = count
|
||||
return count
|
||||
}
|
||||
|
||||
/* Climbing stairs: Memoization search */
|
||||
func climbingStairsDFSMem(n: Int) -> Int {
|
||||
// mem[i] records the total number of solutions to climb to the i-th stair, -1 means no record
|
||||
var mem = Array(repeating: -1, count: n + 1)
|
||||
return dfs(i: n, mem: &mem)
|
||||
}
|
||||
|
||||
@main
|
||||
enum ClimbingStairsDFSMem {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let n = 9
|
||||
|
||||
let res = climbingStairsDFSMem(n: n)
|
||||
print("Climbing \(n) stairs has \(res) solutions")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* File: climbing_stairs_dp.swift
|
||||
* Created Time: 2023-07-15
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Climbing stairs: Dynamic programming */
|
||||
func climbingStairsDP(n: Int) -> Int {
|
||||
if n == 1 || n == 2 {
|
||||
return n
|
||||
}
|
||||
// Initialize dp table, used to store solutions to subproblems
|
||||
var dp = Array(repeating: 0, count: n + 1)
|
||||
// Initial state: preset the solution to the smallest subproblem
|
||||
dp[1] = 1
|
||||
dp[2] = 2
|
||||
// State transition: gradually solve larger subproblems from smaller ones
|
||||
for i in 3 ... n {
|
||||
dp[i] = dp[i - 1] + dp[i - 2]
|
||||
}
|
||||
return dp[n]
|
||||
}
|
||||
|
||||
/* Climbing stairs: Space-optimized dynamic programming */
|
||||
func climbingStairsDPComp(n: Int) -> Int {
|
||||
if n == 1 || n == 2 {
|
||||
return n
|
||||
}
|
||||
var a = 1
|
||||
var b = 2
|
||||
for _ in 3 ... n {
|
||||
(a, b) = (b, a + b)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
@main
|
||||
enum ClimbingStairsDP {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let n = 9
|
||||
|
||||
var res = climbingStairsDP(n: n)
|
||||
print("Climbing \(n) stairs has \(res) solutions")
|
||||
|
||||
res = climbingStairsDPComp(n: n)
|
||||
print("Climbing \(n) stairs has \(res) solutions")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* File: coin_change.swift
|
||||
* Created Time: 2023-07-15
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Coin change: Dynamic programming */
|
||||
func coinChangeDP(coins: [Int], amt: Int) -> Int {
|
||||
let n = coins.count
|
||||
let MAX = amt + 1
|
||||
// Initialize dp table
|
||||
var dp = Array(repeating: Array(repeating: 0, count: amt + 1), count: n + 1)
|
||||
// State transition: first row and first column
|
||||
for a in 1 ... amt {
|
||||
dp[0][a] = MAX
|
||||
}
|
||||
// State transition: rest of the rows and columns
|
||||
for i in 1 ... n {
|
||||
for a in 1 ... amt {
|
||||
if coins[i - 1] > a {
|
||||
// If exceeds target amount, don't select coin i
|
||||
dp[i][a] = dp[i - 1][a]
|
||||
} else {
|
||||
// The smaller value between not selecting and selecting coin i
|
||||
dp[i][a] = min(dp[i - 1][a], dp[i][a - coins[i - 1]] + 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][amt] != MAX ? dp[n][amt] : -1
|
||||
}
|
||||
|
||||
/* Coin change: Space-optimized dynamic programming */
|
||||
func coinChangeDPComp(coins: [Int], amt: Int) -> Int {
|
||||
let n = coins.count
|
||||
let MAX = amt + 1
|
||||
// Initialize dp table
|
||||
var dp = Array(repeating: MAX, count: amt + 1)
|
||||
dp[0] = 0
|
||||
// State transition
|
||||
for i in 1 ... n {
|
||||
for a in 1 ... amt {
|
||||
if coins[i - 1] > a {
|
||||
// If exceeds target amount, don't select coin i
|
||||
dp[a] = dp[a]
|
||||
} else {
|
||||
// The smaller value between not selecting and selecting coin i
|
||||
dp[a] = min(dp[a], dp[a - coins[i - 1]] + 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[amt] != MAX ? dp[amt] : -1
|
||||
}
|
||||
|
||||
@main
|
||||
enum CoinChange {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let coins = [1, 2, 5]
|
||||
let amt = 4
|
||||
|
||||
// Dynamic programming
|
||||
var res = coinChangeDP(coins: coins, amt: amt)
|
||||
print("Minimum coins needed to make target amount is \(res)")
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = coinChangeDPComp(coins: coins, amt: amt)
|
||||
print("Minimum coins needed to make target amount is \(res)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* File: coin_change_ii.swift
|
||||
* Created Time: 2023-07-16
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Coin change II: Dynamic programming */
|
||||
func coinChangeIIDP(coins: [Int], amt: Int) -> Int {
|
||||
let n = coins.count
|
||||
// Initialize dp table
|
||||
var dp = Array(repeating: Array(repeating: 0, count: amt + 1), count: n + 1)
|
||||
// Initialize first column
|
||||
for i in 0 ... n {
|
||||
dp[i][0] = 1
|
||||
}
|
||||
// State transition
|
||||
for i in 1 ... n {
|
||||
for a in 1 ... amt {
|
||||
if coins[i - 1] > a {
|
||||
// If exceeds target amount, don't select coin i
|
||||
dp[i][a] = dp[i - 1][a]
|
||||
} else {
|
||||
// Sum of the two options: not selecting and selecting coin i
|
||||
dp[i][a] = dp[i - 1][a] + dp[i][a - coins[i - 1]]
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][amt]
|
||||
}
|
||||
|
||||
/* Coin change II: Space-optimized dynamic programming */
|
||||
func coinChangeIIDPComp(coins: [Int], amt: Int) -> Int {
|
||||
let n = coins.count
|
||||
// Initialize dp table
|
||||
var dp = Array(repeating: 0, count: amt + 1)
|
||||
dp[0] = 1
|
||||
// State transition
|
||||
for i in 1 ... n {
|
||||
for a in 1 ... amt {
|
||||
if coins[i - 1] > a {
|
||||
// If exceeds target amount, don't select coin i
|
||||
dp[a] = dp[a]
|
||||
} else {
|
||||
// Sum of the two options: not selecting and selecting coin i
|
||||
dp[a] = dp[a] + dp[a - coins[i - 1]]
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[amt]
|
||||
}
|
||||
|
||||
@main
|
||||
enum CoinChangeII {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let coins = [1, 2, 5]
|
||||
let amt = 5
|
||||
|
||||
// Dynamic programming
|
||||
var res = coinChangeIIDP(coins: coins, amt: amt)
|
||||
print("Number of coin combinations to make target amount is \(res)")
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = coinChangeIIDPComp(coins: coins, amt: amt)
|
||||
print("Number of coin combinations to make target amount is \(res)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* File: edit_distance.swift
|
||||
* Created Time: 2023-07-16
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Edit distance: Brute-force search */
|
||||
func editDistanceDFS(s: String, t: String, i: Int, j: Int) -> Int {
|
||||
// If both s and t are empty, return 0
|
||||
if i == 0, j == 0 {
|
||||
return 0
|
||||
}
|
||||
// If s is empty, return length of t
|
||||
if i == 0 {
|
||||
return j
|
||||
}
|
||||
// If t is empty, return length of s
|
||||
if j == 0 {
|
||||
return i
|
||||
}
|
||||
// If two characters are equal, skip both characters
|
||||
if s.utf8CString[i - 1] == t.utf8CString[j - 1] {
|
||||
return editDistanceDFS(s: s, t: t, i: i - 1, j: j - 1)
|
||||
}
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
let insert = editDistanceDFS(s: s, t: t, i: i, j: j - 1)
|
||||
let delete = editDistanceDFS(s: s, t: t, i: i - 1, j: j)
|
||||
let replace = editDistanceDFS(s: s, t: t, i: i - 1, j: j - 1)
|
||||
// Return minimum edit steps
|
||||
return min(min(insert, delete), replace) + 1
|
||||
}
|
||||
|
||||
/* Edit distance: Memoization search */
|
||||
func editDistanceDFSMem(s: String, t: String, mem: inout [[Int]], i: Int, j: Int) -> Int {
|
||||
// If both s and t are empty, return 0
|
||||
if i == 0, j == 0 {
|
||||
return 0
|
||||
}
|
||||
// If s is empty, return length of t
|
||||
if i == 0 {
|
||||
return j
|
||||
}
|
||||
// If t is empty, return length of s
|
||||
if j == 0 {
|
||||
return i
|
||||
}
|
||||
// If there's a record, return it directly
|
||||
if mem[i][j] != -1 {
|
||||
return mem[i][j]
|
||||
}
|
||||
// If two characters are equal, skip both characters
|
||||
if s.utf8CString[i - 1] == t.utf8CString[j - 1] {
|
||||
return editDistanceDFS(s: s, t: t, i: i - 1, j: j - 1)
|
||||
}
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
let insert = editDistanceDFS(s: s, t: t, i: i, j: j - 1)
|
||||
let delete = editDistanceDFS(s: s, t: t, i: i - 1, j: j)
|
||||
let replace = editDistanceDFS(s: s, t: t, i: i - 1, j: j - 1)
|
||||
// Record and return minimum edit steps
|
||||
mem[i][j] = min(min(insert, delete), replace) + 1
|
||||
return mem[i][j]
|
||||
}
|
||||
|
||||
/* Edit distance: Dynamic programming */
|
||||
func editDistanceDP(s: String, t: String) -> Int {
|
||||
let n = s.utf8CString.count
|
||||
let m = t.utf8CString.count
|
||||
var dp = Array(repeating: Array(repeating: 0, count: m + 1), count: n + 1)
|
||||
// State transition: first row and first column
|
||||
for i in 1 ... n {
|
||||
dp[i][0] = i
|
||||
}
|
||||
for j in 1 ... m {
|
||||
dp[0][j] = j
|
||||
}
|
||||
// State transition: rest of the rows and columns
|
||||
for i in 1 ... n {
|
||||
for j in 1 ... m {
|
||||
if s.utf8CString[i - 1] == t.utf8CString[j - 1] {
|
||||
// If two characters are equal, skip both characters
|
||||
dp[i][j] = dp[i - 1][j - 1]
|
||||
} else {
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
dp[i][j] = min(min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][m]
|
||||
}
|
||||
|
||||
/* Edit distance: Space-optimized dynamic programming */
|
||||
func editDistanceDPComp(s: String, t: String) -> Int {
|
||||
let n = s.utf8CString.count
|
||||
let m = t.utf8CString.count
|
||||
var dp = Array(repeating: 0, count: m + 1)
|
||||
// State transition: first row
|
||||
for j in 1 ... m {
|
||||
dp[j] = j
|
||||
}
|
||||
// State transition: rest of the rows
|
||||
for i in 1 ... n {
|
||||
// State transition: first column
|
||||
var leftup = dp[0] // Temporarily store dp[i-1, j-1]
|
||||
dp[0] = i
|
||||
// State transition: rest of the columns
|
||||
for j in 1 ... m {
|
||||
let temp = dp[j]
|
||||
if s.utf8CString[i - 1] == t.utf8CString[j - 1] {
|
||||
// If two characters are equal, skip both characters
|
||||
dp[j] = leftup
|
||||
} else {
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
dp[j] = min(min(dp[j - 1], dp[j]), leftup) + 1
|
||||
}
|
||||
leftup = temp // Update for next round's dp[i-1, j-1]
|
||||
}
|
||||
}
|
||||
return dp[m]
|
||||
}
|
||||
|
||||
@main
|
||||
enum EditDistance {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let s = "bag"
|
||||
let t = "pack"
|
||||
let n = s.utf8CString.count
|
||||
let m = t.utf8CString.count
|
||||
|
||||
// Brute-force search
|
||||
var res = editDistanceDFS(s: s, t: t, i: n, j: m)
|
||||
print("Changing \(s) to \(t) requires minimum \(res) edits")
|
||||
|
||||
// Memoization search
|
||||
var mem = Array(repeating: Array(repeating: -1, count: m + 1), count: n + 1)
|
||||
res = editDistanceDFSMem(s: s, t: t, mem: &mem, i: n, j: m)
|
||||
print("Changing \(s) to \(t) requires minimum \(res) edits")
|
||||
|
||||
// Dynamic programming
|
||||
res = editDistanceDP(s: s, t: t)
|
||||
print("Changing \(s) to \(t) requires minimum \(res) edits")
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = editDistanceDPComp(s: s, t: t)
|
||||
print("Changing \(s) to \(t) requires minimum \(res) edits")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
/**
|
||||
* File: knapsack.swift
|
||||
* Created Time: 2023-07-15
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* 0-1 knapsack: Brute-force search */
|
||||
func knapsackDFS(wgt: [Int], val: [Int], i: Int, c: Int) -> Int {
|
||||
// If all items have been selected or knapsack has no remaining capacity, return value 0
|
||||
if i == 0 || c == 0 {
|
||||
return 0
|
||||
}
|
||||
// If exceeds knapsack capacity, can only choose not to put it in
|
||||
if wgt[i - 1] > c {
|
||||
return knapsackDFS(wgt: wgt, val: val, i: i - 1, c: c)
|
||||
}
|
||||
// Calculate the maximum value of not putting in and putting in item i
|
||||
let no = knapsackDFS(wgt: wgt, val: val, i: i - 1, c: c)
|
||||
let yes = knapsackDFS(wgt: wgt, val: val, i: i - 1, c: c - wgt[i - 1]) + val[i - 1]
|
||||
// Return the larger value of the two options
|
||||
return max(no, yes)
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: Memoization search */
|
||||
func knapsackDFSMem(wgt: [Int], val: [Int], mem: inout [[Int]], i: Int, c: Int) -> Int {
|
||||
// If all items have been selected or knapsack has no remaining capacity, return value 0
|
||||
if i == 0 || c == 0 {
|
||||
return 0
|
||||
}
|
||||
// If there's a record, return it directly
|
||||
if mem[i][c] != -1 {
|
||||
return mem[i][c]
|
||||
}
|
||||
// If exceeds knapsack capacity, can only choose not to put it in
|
||||
if wgt[i - 1] > c {
|
||||
return knapsackDFSMem(wgt: wgt, val: val, mem: &mem, i: i - 1, c: c)
|
||||
}
|
||||
// Calculate the maximum value of not putting in and putting in item i
|
||||
let no = knapsackDFSMem(wgt: wgt, val: val, mem: &mem, i: i - 1, c: c)
|
||||
let yes = knapsackDFSMem(wgt: wgt, val: val, mem: &mem, i: i - 1, c: c - wgt[i - 1]) + val[i - 1]
|
||||
// Record and return the larger value of the two options
|
||||
mem[i][c] = max(no, yes)
|
||||
return mem[i][c]
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: Dynamic programming */
|
||||
func knapsackDP(wgt: [Int], val: [Int], cap: Int) -> Int {
|
||||
let n = wgt.count
|
||||
// Initialize dp table
|
||||
var dp = Array(repeating: Array(repeating: 0, count: cap + 1), count: n + 1)
|
||||
// State transition
|
||||
for i in 1 ... n {
|
||||
for c in 1 ... cap {
|
||||
if wgt[i - 1] > c {
|
||||
// If exceeds knapsack capacity, don't select item i
|
||||
dp[i][c] = dp[i - 1][c]
|
||||
} else {
|
||||
// The larger value between not selecting and selecting item i
|
||||
dp[i][c] = max(dp[i - 1][c], dp[i - 1][c - wgt[i - 1]] + val[i - 1])
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][cap]
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: Space-optimized dynamic programming */
|
||||
func knapsackDPComp(wgt: [Int], val: [Int], cap: Int) -> Int {
|
||||
let n = wgt.count
|
||||
// Initialize dp table
|
||||
var dp = Array(repeating: 0, count: cap + 1)
|
||||
// State transition
|
||||
for i in 1 ... n {
|
||||
// Traverse in reverse order
|
||||
for c in (1 ... cap).reversed() {
|
||||
if wgt[i - 1] <= c {
|
||||
// The larger value between not selecting and selecting item i
|
||||
dp[c] = max(dp[c], dp[c - wgt[i - 1]] + val[i - 1])
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[cap]
|
||||
}
|
||||
|
||||
@main
|
||||
enum Knapsack {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let wgt = [10, 20, 30, 40, 50]
|
||||
let val = [50, 120, 150, 210, 240]
|
||||
let cap = 50
|
||||
let n = wgt.count
|
||||
|
||||
// Brute-force search
|
||||
var res = knapsackDFS(wgt: wgt, val: val, i: n, c: cap)
|
||||
print("Maximum item value not exceeding knapsack capacity is \(res)")
|
||||
|
||||
// Memoization search
|
||||
var mem = Array(repeating: Array(repeating: -1, count: cap + 1), count: n + 1)
|
||||
res = knapsackDFSMem(wgt: wgt, val: val, mem: &mem, i: n, c: cap)
|
||||
print("Maximum item value not exceeding knapsack capacity is \(res)")
|
||||
|
||||
// Dynamic programming
|
||||
res = knapsackDP(wgt: wgt, val: val, cap: cap)
|
||||
print("Maximum item value not exceeding knapsack capacity is \(res)")
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = knapsackDPComp(wgt: wgt, val: val, cap: cap)
|
||||
print("Maximum item value not exceeding knapsack capacity is \(res)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* File: min_cost_climbing_stairs_dp.swift
|
||||
* Created Time: 2023-07-15
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Minimum cost climbing stairs: Dynamic programming */
|
||||
func minCostClimbingStairsDP(cost: [Int]) -> Int {
|
||||
let n = cost.count - 1
|
||||
if n == 1 || n == 2 {
|
||||
return cost[n]
|
||||
}
|
||||
// Initialize dp table, used to store solutions to subproblems
|
||||
var dp = Array(repeating: 0, count: n + 1)
|
||||
// Initial state: preset the solution to the smallest subproblem
|
||||
dp[1] = cost[1]
|
||||
dp[2] = cost[2]
|
||||
// State transition: gradually solve larger subproblems from smaller ones
|
||||
for i in 3 ... n {
|
||||
dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i]
|
||||
}
|
||||
return dp[n]
|
||||
}
|
||||
|
||||
/* Minimum cost climbing stairs: Space-optimized dynamic programming */
|
||||
func minCostClimbingStairsDPComp(cost: [Int]) -> Int {
|
||||
let n = cost.count - 1
|
||||
if n == 1 || n == 2 {
|
||||
return cost[n]
|
||||
}
|
||||
var (a, b) = (cost[1], cost[2])
|
||||
for i in 3 ... n {
|
||||
(a, b) = (b, min(a, b) + cost[i])
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
@main
|
||||
enum MinCostClimbingStairsDP {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let cost = [0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1]
|
||||
print("Input stair cost list is \(cost)")
|
||||
|
||||
var res = minCostClimbingStairsDP(cost: cost)
|
||||
print("Minimum cost to climb stairs is \(res)")
|
||||
|
||||
res = minCostClimbingStairsDPComp(cost: cost)
|
||||
print("Minimum cost to climb stairs is \(res)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* File: min_path_sum.swift
|
||||
* Created Time: 2023-07-15
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Minimum path sum: Brute-force search */
|
||||
func minPathSumDFS(grid: [[Int]], i: Int, j: Int) -> Int {
|
||||
// If it's the top-left cell, terminate the search
|
||||
if i == 0, j == 0 {
|
||||
return grid[0][0]
|
||||
}
|
||||
// If row or column index is out of bounds, return +∞ cost
|
||||
if i < 0 || j < 0 {
|
||||
return .max
|
||||
}
|
||||
// Calculate the minimum path cost from top-left to (i-1, j) and (i, j-1)
|
||||
let up = minPathSumDFS(grid: grid, i: i - 1, j: j)
|
||||
let left = minPathSumDFS(grid: grid, i: i, j: j - 1)
|
||||
// Return the minimum path cost from top-left to (i, j)
|
||||
return min(left, up) + grid[i][j]
|
||||
}
|
||||
|
||||
/* Minimum path sum: Memoization search */
|
||||
func minPathSumDFSMem(grid: [[Int]], mem: inout [[Int]], i: Int, j: Int) -> Int {
|
||||
// If it's the top-left cell, terminate the search
|
||||
if i == 0, j == 0 {
|
||||
return grid[0][0]
|
||||
}
|
||||
// If row or column index is out of bounds, return +∞ cost
|
||||
if i < 0 || j < 0 {
|
||||
return .max
|
||||
}
|
||||
// If there's a record, return it directly
|
||||
if mem[i][j] != -1 {
|
||||
return mem[i][j]
|
||||
}
|
||||
// Minimum path cost for left and upper cells
|
||||
let up = minPathSumDFSMem(grid: grid, mem: &mem, i: i - 1, j: j)
|
||||
let left = minPathSumDFSMem(grid: grid, mem: &mem, i: i, j: j - 1)
|
||||
// Record and return the minimum path cost from top-left to (i, j)
|
||||
mem[i][j] = min(left, up) + grid[i][j]
|
||||
return mem[i][j]
|
||||
}
|
||||
|
||||
/* Minimum path sum: Dynamic programming */
|
||||
func minPathSumDP(grid: [[Int]]) -> Int {
|
||||
let n = grid.count
|
||||
let m = grid[0].count
|
||||
// Initialize dp table
|
||||
var dp = Array(repeating: Array(repeating: 0, count: m), count: n)
|
||||
dp[0][0] = grid[0][0]
|
||||
// State transition: first row
|
||||
for j in 1 ..< m {
|
||||
dp[0][j] = dp[0][j - 1] + grid[0][j]
|
||||
}
|
||||
// State transition: first column
|
||||
for i in 1 ..< n {
|
||||
dp[i][0] = dp[i - 1][0] + grid[i][0]
|
||||
}
|
||||
// State transition: rest of the rows and columns
|
||||
for i in 1 ..< n {
|
||||
for j in 1 ..< m {
|
||||
dp[i][j] = min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j]
|
||||
}
|
||||
}
|
||||
return dp[n - 1][m - 1]
|
||||
}
|
||||
|
||||
/* Minimum path sum: Space-optimized dynamic programming */
|
||||
func minPathSumDPComp(grid: [[Int]]) -> Int {
|
||||
let n = grid.count
|
||||
let m = grid[0].count
|
||||
// Initialize dp table
|
||||
var dp = Array(repeating: 0, count: m)
|
||||
// State transition: first row
|
||||
dp[0] = grid[0][0]
|
||||
for j in 1 ..< m {
|
||||
dp[j] = dp[j - 1] + grid[0][j]
|
||||
}
|
||||
// State transition: rest of the rows
|
||||
for i in 1 ..< n {
|
||||
// State transition: first column
|
||||
dp[0] = dp[0] + grid[i][0]
|
||||
// State transition: rest of the columns
|
||||
for j in 1 ..< m {
|
||||
dp[j] = min(dp[j - 1], dp[j]) + grid[i][j]
|
||||
}
|
||||
}
|
||||
return dp[m - 1]
|
||||
}
|
||||
|
||||
@main
|
||||
enum MinPathSum {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let grid = [
|
||||
[1, 3, 1, 5],
|
||||
[2, 2, 4, 2],
|
||||
[5, 3, 2, 1],
|
||||
[4, 3, 5, 2],
|
||||
]
|
||||
let n = grid.count
|
||||
let m = grid[0].count
|
||||
|
||||
// Brute-force search
|
||||
var res = minPathSumDFS(grid: grid, i: n - 1, j: m - 1)
|
||||
print("Minimum path sum from top-left to bottom-right is \(res)")
|
||||
|
||||
// Memoization search
|
||||
var mem = Array(repeating: Array(repeating: -1, count: m), count: n)
|
||||
res = minPathSumDFSMem(grid: grid, mem: &mem, i: n - 1, j: m - 1)
|
||||
print("Minimum path sum from top-left to bottom-right is \(res)")
|
||||
|
||||
// Dynamic programming
|
||||
res = minPathSumDP(grid: grid)
|
||||
print("Minimum path sum from top-left to bottom-right is \(res)")
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = minPathSumDPComp(grid: grid)
|
||||
print("Minimum path sum from top-left to bottom-right is \(res)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* File: unbounded_knapsack.swift
|
||||
* Created Time: 2023-07-15
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Unbounded knapsack: Dynamic programming */
|
||||
func unboundedKnapsackDP(wgt: [Int], val: [Int], cap: Int) -> Int {
|
||||
let n = wgt.count
|
||||
// Initialize dp table
|
||||
var dp = Array(repeating: Array(repeating: 0, count: cap + 1), count: n + 1)
|
||||
// State transition
|
||||
for i in 1 ... n {
|
||||
for c in 1 ... cap {
|
||||
if wgt[i - 1] > c {
|
||||
// If exceeds knapsack capacity, don't select item i
|
||||
dp[i][c] = dp[i - 1][c]
|
||||
} else {
|
||||
// The larger value between not selecting and selecting item i
|
||||
dp[i][c] = max(dp[i - 1][c], dp[i][c - wgt[i - 1]] + val[i - 1])
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][cap]
|
||||
}
|
||||
|
||||
/* Unbounded knapsack: Space-optimized dynamic programming */
|
||||
func unboundedKnapsackDPComp(wgt: [Int], val: [Int], cap: Int) -> Int {
|
||||
let n = wgt.count
|
||||
// Initialize dp table
|
||||
var dp = Array(repeating: 0, count: cap + 1)
|
||||
// State transition
|
||||
for i in 1 ... n {
|
||||
for c in 1 ... cap {
|
||||
if wgt[i - 1] > c {
|
||||
// If exceeds knapsack capacity, don't select item i
|
||||
dp[c] = dp[c]
|
||||
} else {
|
||||
// The larger value between not selecting and selecting item i
|
||||
dp[c] = max(dp[c], dp[c - wgt[i - 1]] + val[i - 1])
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[cap]
|
||||
}
|
||||
|
||||
@main
|
||||
enum UnboundedKnapsack {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let wgt = [1, 2, 3]
|
||||
let val = [5, 11, 15]
|
||||
let cap = 4
|
||||
|
||||
// Dynamic programming
|
||||
var res = unboundedKnapsackDP(wgt: wgt, val: val, cap: cap)
|
||||
print("Maximum item value not exceeding knapsack capacity is \(res)")
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = unboundedKnapsackDPComp(wgt: wgt, val: val, cap: cap)
|
||||
print("Maximum item value not exceeding knapsack capacity is \(res)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* File: graph_adjacency_list.swift
|
||||
* Created Time: 2023-02-01
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
import utils
|
||||
|
||||
/* Undirected graph class based on adjacency list */
|
||||
public class GraphAdjList {
|
||||
// Adjacency list, key: vertex, value: all adjacent vertices of that vertex
|
||||
public private(set) var adjList: [Vertex: [Vertex]]
|
||||
|
||||
/* Constructor */
|
||||
public init(edges: [[Vertex]]) {
|
||||
adjList = [:]
|
||||
// Add all vertices and edges
|
||||
for edge in edges {
|
||||
addVertex(vet: edge[0])
|
||||
addVertex(vet: edge[1])
|
||||
addEdge(vet1: edge[0], vet2: edge[1])
|
||||
}
|
||||
}
|
||||
|
||||
/* Get the number of vertices */
|
||||
public func size() -> Int {
|
||||
adjList.count
|
||||
}
|
||||
|
||||
/* Add edge */
|
||||
public func addEdge(vet1: Vertex, vet2: Vertex) {
|
||||
if adjList[vet1] == nil || adjList[vet2] == nil || vet1 == vet2 {
|
||||
fatalError("Invalid parameter")
|
||||
}
|
||||
// Add edge vet1 - vet2
|
||||
adjList[vet1]?.append(vet2)
|
||||
adjList[vet2]?.append(vet1)
|
||||
}
|
||||
|
||||
/* Remove edge */
|
||||
public func removeEdge(vet1: Vertex, vet2: Vertex) {
|
||||
if adjList[vet1] == nil || adjList[vet2] == nil || vet1 == vet2 {
|
||||
fatalError("Invalid parameter")
|
||||
}
|
||||
// Remove edge vet1 - vet2
|
||||
adjList[vet1]?.removeAll { $0 == vet2 }
|
||||
adjList[vet2]?.removeAll { $0 == vet1 }
|
||||
}
|
||||
|
||||
/* Add vertex */
|
||||
public func addVertex(vet: Vertex) {
|
||||
if adjList[vet] != nil {
|
||||
return
|
||||
}
|
||||
// Add a new linked list in the adjacency list
|
||||
adjList[vet] = []
|
||||
}
|
||||
|
||||
/* Remove vertex */
|
||||
public func removeVertex(vet: Vertex) {
|
||||
if adjList[vet] == nil {
|
||||
fatalError("Invalid parameter")
|
||||
}
|
||||
// Remove the linked list corresponding to vertex vet in the adjacency list
|
||||
adjList.removeValue(forKey: vet)
|
||||
// Traverse the linked lists of other vertices and remove all edges containing vet
|
||||
for key in adjList.keys {
|
||||
adjList[key]?.removeAll { $0 == vet }
|
||||
}
|
||||
}
|
||||
|
||||
/* Print adjacency list */
|
||||
public func print() {
|
||||
Swift.print("Adjacency list =")
|
||||
for (vertex, list) in adjList {
|
||||
let list = list.map { $0.val }
|
||||
Swift.print("\(vertex.val): \(list),")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if !TARGET
|
||||
|
||||
@main
|
||||
enum GraphAdjacencyList {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
/* Add edge */
|
||||
let v = Vertex.valsToVets(vals: [1, 3, 2, 5, 4])
|
||||
let edges = [[v[0], v[1]], [v[0], v[3]], [v[1], v[2]], [v[2], v[3]], [v[2], v[4]], [v[3], v[4]]]
|
||||
let graph = GraphAdjList(edges: edges)
|
||||
print("\nAfter initialization, graph is")
|
||||
graph.print()
|
||||
|
||||
/* Add edge */
|
||||
// Vertices 1, 3 are v[0], v[1]
|
||||
graph.addEdge(vet1: v[0], vet2: v[2])
|
||||
print("\nAfter adding edge 1-2, graph is")
|
||||
graph.print()
|
||||
|
||||
/* Remove edge */
|
||||
// Vertex 3 is v[1]
|
||||
graph.removeEdge(vet1: v[0], vet2: v[1])
|
||||
print("\nAfter removing edge 1-3, graph is")
|
||||
graph.print()
|
||||
|
||||
/* Add vertex */
|
||||
let v5 = Vertex(val: 6)
|
||||
graph.addVertex(vet: v5)
|
||||
print("\nAfter adding vertex 6, graph is")
|
||||
graph.print()
|
||||
|
||||
/* Remove vertex */
|
||||
// Vertex 3 is v[1]
|
||||
graph.removeVertex(vet: v[1])
|
||||
print("\nAfter removing vertex 3, graph is")
|
||||
graph.print()
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* File: graph_adjacency_list.swift
|
||||
* Created Time: 2023-02-01
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
import utils
|
||||
|
||||
/* Undirected graph class based on adjacency list */
|
||||
public class GraphAdjList {
|
||||
// Adjacency list, key: vertex, value: all adjacent vertices of that vertex
|
||||
public private(set) var adjList: [Vertex: [Vertex]]
|
||||
|
||||
/* Constructor */
|
||||
public init(edges: [[Vertex]]) {
|
||||
adjList = [:]
|
||||
// Add all vertices and edges
|
||||
for edge in edges {
|
||||
addVertex(vet: edge[0])
|
||||
addVertex(vet: edge[1])
|
||||
addEdge(vet1: edge[0], vet2: edge[1])
|
||||
}
|
||||
}
|
||||
|
||||
/* Get the number of vertices */
|
||||
public func size() -> Int {
|
||||
adjList.count
|
||||
}
|
||||
|
||||
/* Add edge */
|
||||
public func addEdge(vet1: Vertex, vet2: Vertex) {
|
||||
if adjList[vet1] == nil || adjList[vet2] == nil || vet1 == vet2 {
|
||||
fatalError("Invalid parameter")
|
||||
}
|
||||
// Add edge vet1 - vet2
|
||||
adjList[vet1]?.append(vet2)
|
||||
adjList[vet2]?.append(vet1)
|
||||
}
|
||||
|
||||
/* Remove edge */
|
||||
public func removeEdge(vet1: Vertex, vet2: Vertex) {
|
||||
if adjList[vet1] == nil || adjList[vet2] == nil || vet1 == vet2 {
|
||||
fatalError("Invalid parameter")
|
||||
}
|
||||
// Remove edge vet1 - vet2
|
||||
adjList[vet1]?.removeAll { $0 == vet2 }
|
||||
adjList[vet2]?.removeAll { $0 == vet1 }
|
||||
}
|
||||
|
||||
/* Add vertex */
|
||||
public func addVertex(vet: Vertex) {
|
||||
if adjList[vet] != nil {
|
||||
return
|
||||
}
|
||||
// Add a new linked list in the adjacency list
|
||||
adjList[vet] = []
|
||||
}
|
||||
|
||||
/* Remove vertex */
|
||||
public func removeVertex(vet: Vertex) {
|
||||
if adjList[vet] == nil {
|
||||
fatalError("Invalid parameter")
|
||||
}
|
||||
// Remove the linked list corresponding to vertex vet in the adjacency list
|
||||
adjList.removeValue(forKey: vet)
|
||||
// Traverse the linked lists of other vertices and remove all edges containing vet
|
||||
for key in adjList.keys {
|
||||
adjList[key]?.removeAll { $0 == vet }
|
||||
}
|
||||
}
|
||||
|
||||
/* Print adjacency list */
|
||||
public func print() {
|
||||
Swift.print("Adjacency list =")
|
||||
for (vertex, list) in adjList {
|
||||
let list = list.map { $0.val }
|
||||
Swift.print("\(vertex.val): \(list),")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if !TARGET
|
||||
|
||||
@main
|
||||
enum GraphAdjacencyList {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
/* Add edge */
|
||||
let v = Vertex.valsToVets(vals: [1, 3, 2, 5, 4])
|
||||
let edges = [[v[0], v[1]], [v[0], v[3]], [v[1], v[2]], [v[2], v[3]], [v[2], v[4]], [v[3], v[4]]]
|
||||
let graph = GraphAdjList(edges: edges)
|
||||
print("\nAfter initialization, graph is")
|
||||
graph.print()
|
||||
|
||||
/* Add edge */
|
||||
// Vertices 1, 3 are v[0], v[1]
|
||||
graph.addEdge(vet1: v[0], vet2: v[2])
|
||||
print("\nAfter adding edge 1-2, graph is")
|
||||
graph.print()
|
||||
|
||||
/* Remove edge */
|
||||
// Vertex 3 is v[1]
|
||||
graph.removeEdge(vet1: v[0], vet2: v[1])
|
||||
print("\nAfter removing edge 1-3, graph is")
|
||||
graph.print()
|
||||
|
||||
/* Add vertex */
|
||||
let v5 = Vertex(val: 6)
|
||||
graph.addVertex(vet: v5)
|
||||
print("\nAfter adding vertex 6, graph is")
|
||||
graph.print()
|
||||
|
||||
/* Remove vertex */
|
||||
// Vertex 3 is v[1]
|
||||
graph.removeVertex(vet: v[1])
|
||||
print("\nAfter removing vertex 3, graph is")
|
||||
graph.print()
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,130 @@
|
||||
/**
|
||||
* File: graph_adjacency_matrix.swift
|
||||
* Created Time: 2023-02-01
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
import utils
|
||||
|
||||
/* Undirected graph class based on adjacency matrix */
|
||||
class GraphAdjMat {
|
||||
private var vertices: [Int] // Vertex list, where the element represents the "vertex value" and the index represents the "vertex index"
|
||||
private var adjMat: [[Int]] // Adjacency matrix, where the row and column indices correspond to the "vertex index"
|
||||
|
||||
/* Constructor */
|
||||
init(vertices: [Int], edges: [[Int]]) {
|
||||
self.vertices = []
|
||||
adjMat = []
|
||||
// Add vertex
|
||||
for val in vertices {
|
||||
addVertex(val: val)
|
||||
}
|
||||
// Add edge
|
||||
// Note that the edges elements represent vertex indices, i.e., corresponding to the vertices element indices
|
||||
for e in edges {
|
||||
addEdge(i: e[0], j: e[1])
|
||||
}
|
||||
}
|
||||
|
||||
/* Get the number of vertices */
|
||||
func size() -> Int {
|
||||
vertices.count
|
||||
}
|
||||
|
||||
/* Add vertex */
|
||||
func addVertex(val: Int) {
|
||||
let n = size()
|
||||
// Add the value of the new vertex to the vertex list
|
||||
vertices.append(val)
|
||||
// Add a row to the adjacency matrix
|
||||
let newRow = Array(repeating: 0, count: n)
|
||||
adjMat.append(newRow)
|
||||
// Add a column to the adjacency matrix
|
||||
for i in adjMat.indices {
|
||||
adjMat[i].append(0)
|
||||
}
|
||||
}
|
||||
|
||||
/* Remove vertex */
|
||||
func removeVertex(index: Int) {
|
||||
if index >= size() {
|
||||
fatalError("Out of bounds")
|
||||
}
|
||||
// Remove the vertex at index from the vertex list
|
||||
vertices.remove(at: index)
|
||||
// Remove the row at index from the adjacency matrix
|
||||
adjMat.remove(at: index)
|
||||
// Remove the column at index from the adjacency matrix
|
||||
for i in adjMat.indices {
|
||||
adjMat[i].remove(at: index)
|
||||
}
|
||||
}
|
||||
|
||||
/* Add edge */
|
||||
// Parameters i, j correspond to the vertices element indices
|
||||
func addEdge(i: Int, j: Int) {
|
||||
// Handle index out of bounds and equality
|
||||
if i < 0 || j < 0 || i >= size() || j >= size() || i == j {
|
||||
fatalError("Out of bounds")
|
||||
}
|
||||
// In an undirected graph, the adjacency matrix is symmetric about the main diagonal, i.e., (i, j) == (j, i)
|
||||
adjMat[i][j] = 1
|
||||
adjMat[j][i] = 1
|
||||
}
|
||||
|
||||
/* Remove edge */
|
||||
// Parameters i, j correspond to the vertices element indices
|
||||
func removeEdge(i: Int, j: Int) {
|
||||
// Handle index out of bounds and equality
|
||||
if i < 0 || j < 0 || i >= size() || j >= size() || i == j {
|
||||
fatalError("Out of bounds")
|
||||
}
|
||||
adjMat[i][j] = 0
|
||||
adjMat[j][i] = 0
|
||||
}
|
||||
|
||||
/* Print adjacency matrix */
|
||||
func print() {
|
||||
Swift.print("Vertex list = ", terminator: "")
|
||||
Swift.print(vertices)
|
||||
Swift.print("Adjacency matrix =")
|
||||
PrintUtil.printMatrix(matrix: adjMat)
|
||||
}
|
||||
}
|
||||
|
||||
@main
|
||||
enum GraphAdjacencyMatrix {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
/* Add edge */
|
||||
// Note that the edges elements represent vertex indices, i.e., corresponding to the vertices element indices
|
||||
let vertices = [1, 3, 2, 5, 4]
|
||||
let edges = [[0, 1], [1, 2], [2, 3], [0, 3], [2, 4], [3, 4]]
|
||||
let graph = GraphAdjMat(vertices: vertices, edges: edges)
|
||||
print("\nAfter initialization, graph is")
|
||||
graph.print()
|
||||
|
||||
/* Add edge */
|
||||
// Add vertex
|
||||
graph.addEdge(i: 0, j: 2)
|
||||
print("\nAfter adding edge 1-2, graph is")
|
||||
graph.print()
|
||||
|
||||
/* Remove edge */
|
||||
// Vertices 1, 3 have indices 0, 1 respectively
|
||||
graph.removeEdge(i: 0, j: 1)
|
||||
print("\nAfter removing edge 1-3, graph is")
|
||||
graph.print()
|
||||
|
||||
/* Add vertex */
|
||||
graph.addVertex(val: 6)
|
||||
print("\nAfter adding vertex 6, graph is")
|
||||
graph.print()
|
||||
|
||||
/* Remove vertex */
|
||||
// Vertex 3 has index 1
|
||||
graph.removeVertex(index: 1)
|
||||
print("\nAfter removing vertex 3, graph is")
|
||||
graph.print()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* File: graph_bfs.swift
|
||||
* Created Time: 2023-02-21
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
import graph_adjacency_list_target
|
||||
import utils
|
||||
|
||||
/* Breadth-first traversal */
|
||||
// Use adjacency list to represent the graph, in order to obtain all adjacent vertices of a specified vertex
|
||||
func graphBFS(graph: GraphAdjList, startVet: Vertex) -> [Vertex] {
|
||||
// Vertex traversal sequence
|
||||
var res: [Vertex] = []
|
||||
// Hash set for recording vertices that have been visited
|
||||
var visited: Set<Vertex> = [startVet]
|
||||
// Queue used to implement BFS
|
||||
var que: [Vertex] = [startVet]
|
||||
// Starting from vertex vet, loop until all vertices are visited
|
||||
while !que.isEmpty {
|
||||
let vet = que.removeFirst() // Dequeue the front vertex
|
||||
res.append(vet) // Record visited vertex
|
||||
// Traverse all adjacent vertices of this vertex
|
||||
for adjVet in graph.adjList[vet] ?? [] {
|
||||
if visited.contains(adjVet) {
|
||||
continue // Skip vertices that have been visited
|
||||
}
|
||||
que.append(adjVet) // Only enqueue unvisited vertices
|
||||
visited.insert(adjVet) // Mark this vertex as visited
|
||||
}
|
||||
}
|
||||
// Return vertex traversal sequence
|
||||
return res
|
||||
}
|
||||
|
||||
@main
|
||||
enum GraphBFS {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
/* Add edge */
|
||||
let v = Vertex.valsToVets(vals: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
|
||||
let edges = [
|
||||
[v[0], v[1]], [v[0], v[3]], [v[1], v[2]], [v[1], v[4]],
|
||||
[v[2], v[5]], [v[3], v[4]], [v[3], v[6]], [v[4], v[5]],
|
||||
[v[4], v[7]], [v[5], v[8]], [v[6], v[7]], [v[7], v[8]],
|
||||
]
|
||||
let graph = GraphAdjList(edges: edges)
|
||||
print("\nAfter initialization, graph is")
|
||||
graph.print()
|
||||
|
||||
/* Breadth-first traversal */
|
||||
let res = graphBFS(graph: graph, startVet: v[0])
|
||||
print("\nBreadth-first traversal (BFS) vertex sequence is")
|
||||
print(Vertex.vetsToVals(vets: res))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* File: graph_dfs.swift
|
||||
* Created Time: 2023-02-21
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
import graph_adjacency_list_target
|
||||
import utils
|
||||
|
||||
/* Depth-first traversal helper function */
|
||||
func dfs(graph: GraphAdjList, visited: inout Set<Vertex>, res: inout [Vertex], vet: Vertex) {
|
||||
res.append(vet) // Record visited vertex
|
||||
visited.insert(vet) // Mark this vertex as visited
|
||||
// Traverse all adjacent vertices of this vertex
|
||||
for adjVet in graph.adjList[vet] ?? [] {
|
||||
if visited.contains(adjVet) {
|
||||
continue // Skip vertices that have been visited
|
||||
}
|
||||
// Recursively visit adjacent vertices
|
||||
dfs(graph: graph, visited: &visited, res: &res, vet: adjVet)
|
||||
}
|
||||
}
|
||||
|
||||
/* Depth-first traversal */
|
||||
// Use adjacency list to represent the graph, in order to obtain all adjacent vertices of a specified vertex
|
||||
func graphDFS(graph: GraphAdjList, startVet: Vertex) -> [Vertex] {
|
||||
// Vertex traversal sequence
|
||||
var res: [Vertex] = []
|
||||
// Hash set for recording vertices that have been visited
|
||||
var visited: Set<Vertex> = []
|
||||
dfs(graph: graph, visited: &visited, res: &res, vet: startVet)
|
||||
return res
|
||||
}
|
||||
|
||||
@main
|
||||
enum GraphDFS {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
/* Add edge */
|
||||
let v = Vertex.valsToVets(vals: [0, 1, 2, 3, 4, 5, 6])
|
||||
let edges = [
|
||||
[v[0], v[1]], [v[0], v[3]], [v[1], v[2]],
|
||||
[v[2], v[5]], [v[4], v[5]], [v[5], v[6]],
|
||||
]
|
||||
let graph = GraphAdjList(edges: edges)
|
||||
print("\nAfter initialization, graph is")
|
||||
graph.print()
|
||||
|
||||
/* Depth-first traversal */
|
||||
let res = graphDFS(graph: graph, startVet: v[0])
|
||||
print("\nDepth-first traversal (DFS) vertex sequence is")
|
||||
print(Vertex.vetsToVals(vets: res))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* File: coin_change_greedy.swift
|
||||
* Created Time: 2023-09-03
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Coin change: Greedy algorithm */
|
||||
func coinChangeGreedy(coins: [Int], amt: Int) -> Int {
|
||||
// Assume coins list is sorted
|
||||
var i = coins.count - 1
|
||||
var count = 0
|
||||
var amt = amt
|
||||
// Loop to make greedy choices until no remaining amount
|
||||
while amt > 0 {
|
||||
// Find the coin that is less than and closest to the remaining amount
|
||||
while i > 0 && coins[i] > amt {
|
||||
i -= 1
|
||||
}
|
||||
// Choose coins[i]
|
||||
amt -= coins[i]
|
||||
count += 1
|
||||
}
|
||||
// If no feasible solution is found, return -1
|
||||
return amt == 0 ? count : -1
|
||||
}
|
||||
|
||||
@main
|
||||
enum CoinChangeGreedy {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
// Greedy algorithm: Can guarantee finding the global optimal solution
|
||||
var coins = [1, 5, 10, 20, 50, 100]
|
||||
var amt = 186
|
||||
var res = coinChangeGreedy(coins: coins, amt: amt)
|
||||
print("\ncoins = \(coins), amount = \(amt)")
|
||||
print("Minimum coins needed to make \(amt) is \(res)")
|
||||
|
||||
// Greedy algorithm: Cannot guarantee finding the global optimal solution
|
||||
coins = [1, 20, 50]
|
||||
amt = 60
|
||||
res = coinChangeGreedy(coins: coins, amt: amt)
|
||||
print("\ncoins = \(coins), amount = \(amt)")
|
||||
print("Minimum coins needed to make \(amt) is \(res)")
|
||||
print("Actually the minimum number needed is 3, i.e., 20 + 20 + 20")
|
||||
|
||||
// Greedy algorithm: Cannot guarantee finding the global optimal solution
|
||||
coins = [1, 49, 50]
|
||||
amt = 98
|
||||
res = coinChangeGreedy(coins: coins, amt: amt)
|
||||
print("\ncoins = \(coins), amount = \(amt)")
|
||||
print("Minimum coins needed to make \(amt) is \(res)")
|
||||
print("Actually the minimum number needed is 2, i.e., 49 + 49")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* File: fractional_knapsack.swift
|
||||
* Created Time: 2023-09-03
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Item */
|
||||
class Item {
|
||||
var w: Int // Item weight
|
||||
var v: Int // Item value
|
||||
|
||||
init(w: Int, v: Int) {
|
||||
self.w = w
|
||||
self.v = v
|
||||
}
|
||||
}
|
||||
|
||||
/* Fractional knapsack: Greedy algorithm */
|
||||
func fractionalKnapsack(wgt: [Int], val: [Int], cap: Int) -> Double {
|
||||
// Create item list with two attributes: weight, value
|
||||
var items = zip(wgt, val).map { Item(w: $0, v: $1) }
|
||||
// Sort by unit value item.v / item.w from high to low
|
||||
items.sort { -(Double($0.v) / Double($0.w)) < -(Double($1.v) / Double($1.w)) }
|
||||
// Loop for greedy selection
|
||||
var res = 0.0
|
||||
var cap = cap
|
||||
for item in items {
|
||||
if item.w <= cap {
|
||||
// If remaining capacity is sufficient, put the entire current item into the knapsack
|
||||
res += Double(item.v)
|
||||
cap -= item.w
|
||||
} else {
|
||||
// If remaining capacity is insufficient, put part of the current item into the knapsack
|
||||
res += Double(item.v) / Double(item.w) * Double(cap)
|
||||
// No remaining capacity, so break out of the loop
|
||||
break
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
@main
|
||||
enum FractionalKnapsack {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
// Item weight
|
||||
let wgt = [10, 20, 30, 40, 50]
|
||||
// Item value
|
||||
let val = [50, 120, 150, 210, 240]
|
||||
// Knapsack capacity
|
||||
let cap = 50
|
||||
|
||||
// Greedy algorithm
|
||||
let res = fractionalKnapsack(wgt: wgt, val: val, cap: cap)
|
||||
print("Maximum item value not exceeding knapsack capacity is \(res)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* File: max_capacity.swift
|
||||
* Created Time: 2023-09-03
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Max capacity: Greedy algorithm */
|
||||
func maxCapacity(ht: [Int]) -> Int {
|
||||
// Initialize i, j to be at both ends of the array
|
||||
var i = ht.startIndex, j = ht.endIndex - 1
|
||||
// Initial max capacity is 0
|
||||
var res = 0
|
||||
// Loop for greedy selection until the two boards meet
|
||||
while i < j {
|
||||
// Update max capacity
|
||||
let cap = min(ht[i], ht[j]) * (j - i)
|
||||
res = max(res, cap)
|
||||
// Move the shorter board inward
|
||||
if ht[i] < ht[j] {
|
||||
i += 1
|
||||
} else {
|
||||
j -= 1
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
@main
|
||||
enum MaxCapacity {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let ht = [3, 8, 5, 2, 7, 7, 3, 4]
|
||||
|
||||
// Greedy algorithm
|
||||
let res = maxCapacity(ht: ht)
|
||||
print("Maximum capacity is \(res)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* File: max_product_cutting.swift
|
||||
* Created Time: 2023-09-03
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
import Foundation
|
||||
|
||||
func pow(_ x: Int, _ y: Int) -> Int {
|
||||
Int(Double(truncating: pow(Decimal(x), y) as NSDecimalNumber))
|
||||
}
|
||||
|
||||
/* Max product cutting: Greedy algorithm */
|
||||
func maxProductCutting(n: Int) -> Int {
|
||||
// When n <= 3, must cut out a 1
|
||||
if n <= 3 {
|
||||
return 1 * (n - 1)
|
||||
}
|
||||
// Greedily cut out 3, a is the number of 3s, b is the remainder
|
||||
let a = n / 3
|
||||
let b = n % 3
|
||||
if b == 1 {
|
||||
// When the remainder is 1, convert a pair of 1 * 3 to 2 * 2
|
||||
return pow(3, a - 1) * 2 * 2
|
||||
}
|
||||
if b == 2 {
|
||||
// When the remainder is 2, do nothing
|
||||
return pow(3, a) * 2
|
||||
}
|
||||
// When the remainder is 0, do nothing
|
||||
return pow(3, a)
|
||||
}
|
||||
|
||||
@main
|
||||
enum MaxProductCutting {
|
||||
static func main() {
|
||||
let n = 58
|
||||
|
||||
// Greedy algorithm
|
||||
let res = maxProductCutting(n: n)
|
||||
print("Maximum cutting product is \(res)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
/**
|
||||
* File: array_hash_map.swift
|
||||
* Created Time: 2023-01-16
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
import utils
|
||||
|
||||
/* Hash table based on array implementation */
|
||||
class ArrayHashMap {
|
||||
private var buckets: [Pair?]
|
||||
|
||||
init() {
|
||||
// Initialize array with 100 buckets
|
||||
buckets = Array(repeating: nil, count: 100)
|
||||
}
|
||||
|
||||
/* Hash function */
|
||||
private func hashFunc(key: Int) -> Int {
|
||||
let index = key % 100
|
||||
return index
|
||||
}
|
||||
|
||||
/* Query operation */
|
||||
func get(key: Int) -> String? {
|
||||
let index = hashFunc(key: key)
|
||||
let pair = buckets[index]
|
||||
return pair?.val
|
||||
}
|
||||
|
||||
/* Add operation */
|
||||
func put(key: Int, val: String) {
|
||||
let pair = Pair(key: key, val: val)
|
||||
let index = hashFunc(key: key)
|
||||
buckets[index] = pair
|
||||
}
|
||||
|
||||
/* Remove operation */
|
||||
func remove(key: Int) {
|
||||
let index = hashFunc(key: key)
|
||||
// Set to nil to delete
|
||||
buckets[index] = nil
|
||||
}
|
||||
|
||||
/* Get all key-value pairs */
|
||||
func pairSet() -> [Pair] {
|
||||
buckets.compactMap { $0 }
|
||||
}
|
||||
|
||||
/* Get all keys */
|
||||
func keySet() -> [Int] {
|
||||
buckets.compactMap { $0?.key }
|
||||
}
|
||||
|
||||
/* Get all values */
|
||||
func valueSet() -> [String] {
|
||||
buckets.compactMap { $0?.val }
|
||||
}
|
||||
|
||||
/* Print hash table */
|
||||
func print() {
|
||||
for pair in pairSet() {
|
||||
Swift.print("\(pair.key) -> \(pair.val)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@main
|
||||
enum _ArrayHashMap {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
/* Initialize hash table */
|
||||
let map = ArrayHashMap()
|
||||
|
||||
/* Add operation */
|
||||
// Add key-value pair (key, value) to the hash table
|
||||
map.put(key: 12836, val: "Xiao Ha")
|
||||
map.put(key: 15937, val: "Xiao Luo")
|
||||
map.put(key: 16750, val: "Xiao Suan")
|
||||
map.put(key: 13276, val: "Xiao Fa")
|
||||
map.put(key: 10583, val: "Xiao Ya")
|
||||
print("\nAfter adding is complete, hash table is\nKey -> Value")
|
||||
map.print()
|
||||
|
||||
/* Query operation */
|
||||
// Input key into hash table to get value
|
||||
let name = map.get(key: 15937)!
|
||||
print("\nInput student ID 15937, found name \(name)")
|
||||
|
||||
/* Remove operation */
|
||||
// Remove key-value pair (key, value) from hash table
|
||||
map.remove(key: 10583)
|
||||
print("\nAfter removing 10583, hash table is\nKey -> Value")
|
||||
map.print()
|
||||
|
||||
/* Traverse hash table */
|
||||
print("\nTraverse key-value pairs Key->Value")
|
||||
for pair in map.pairSet() {
|
||||
print("\(pair.key) -> \(pair.val)")
|
||||
}
|
||||
print("\nTraverse keys only Key")
|
||||
for key in map.keySet() {
|
||||
print(key)
|
||||
}
|
||||
print("\nTraverse values only Value")
|
||||
for val in map.valueSet() {
|
||||
print(val)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* File: built_in_hash.swift
|
||||
* Created Time: 2023-07-01
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
import utils
|
||||
|
||||
@main
|
||||
enum BuiltInHash {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let num = 3
|
||||
let hashNum = num.hashValue
|
||||
print("Hash value of integer \(num) is \(hashNum)")
|
||||
|
||||
let bol = true
|
||||
let hashBol = bol.hashValue
|
||||
print("Hash value of boolean \(bol) is \(hashBol)")
|
||||
|
||||
let dec = 3.14159
|
||||
let hashDec = dec.hashValue
|
||||
print("Hash value of decimal \(dec) is \(hashDec)")
|
||||
|
||||
let str = "Hello Algo"
|
||||
let hashStr = str.hashValue
|
||||
print("Hash value of string \(str) is \(hashStr)")
|
||||
|
||||
let arr = [AnyHashable(12836), AnyHashable("Xiao Ha")]
|
||||
let hashTup = arr.hashValue
|
||||
print("Hash value of array \(arr) is \(hashTup)")
|
||||
|
||||
let obj = ListNode(x: 0)
|
||||
let hashObj = obj.hashValue
|
||||
print("Hash value of node object \(obj) is \(hashObj)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* File: hash_map.swift
|
||||
* Created Time: 2023-01-16
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
import utils
|
||||
|
||||
@main
|
||||
enum HashMap {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
/* Initialize hash table */
|
||||
var map: [Int: String] = [:]
|
||||
|
||||
/* Add operation */
|
||||
// Add key-value pair (key, value) to the hash table
|
||||
map[12836] = "Xiao Ha"
|
||||
map[15937] = "Xiao Luo"
|
||||
map[16750] = "Xiao Suan"
|
||||
map[13276] = "Xiao Fa"
|
||||
map[10583] = "Xiao Ya"
|
||||
print("\nAfter adding is complete, hash table is\nKey -> Value")
|
||||
PrintUtil.printHashMap(map: map)
|
||||
|
||||
/* Query operation */
|
||||
// Input key into hash table to get value
|
||||
let name = map[15937]!
|
||||
print("\nInput student ID 15937, found name \(name)")
|
||||
|
||||
/* Remove operation */
|
||||
// Remove key-value pair (key, value) from hash table
|
||||
map.removeValue(forKey: 10583)
|
||||
print("\nAfter removing 10583, hash table is\nKey -> Value")
|
||||
PrintUtil.printHashMap(map: map)
|
||||
|
||||
/* Traverse hash table */
|
||||
print("\nTraverse key-value pairs Key->Value")
|
||||
for (key, value) in map {
|
||||
print("\(key) -> \(value)")
|
||||
}
|
||||
print("\nTraverse keys only Key")
|
||||
for key in map.keys {
|
||||
print(key)
|
||||
}
|
||||
print("\nTraverse values only Value")
|
||||
for value in map.values {
|
||||
print(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
/**
|
||||
* File: hash_map_chaining.swift
|
||||
* Created Time: 2023-06-28
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
import utils
|
||||
|
||||
/* Hash table with separate chaining */
|
||||
class HashMapChaining {
|
||||
var size: Int // Number of key-value pairs
|
||||
var capacity: Int // Hash table capacity
|
||||
var loadThres: Double // Load factor threshold for triggering expansion
|
||||
var extendRatio: Int // Expansion multiplier
|
||||
var buckets: [[Pair]] // Bucket array
|
||||
|
||||
/* Constructor */
|
||||
init() {
|
||||
size = 0
|
||||
capacity = 4
|
||||
loadThres = 2.0 / 3.0
|
||||
extendRatio = 2
|
||||
buckets = Array(repeating: [], count: capacity)
|
||||
}
|
||||
|
||||
/* Hash function */
|
||||
func hashFunc(key: Int) -> Int {
|
||||
key % capacity
|
||||
}
|
||||
|
||||
/* Load factor */
|
||||
func loadFactor() -> Double {
|
||||
Double(size) / Double(capacity)
|
||||
}
|
||||
|
||||
/* Query operation */
|
||||
func get(key: Int) -> String? {
|
||||
let index = hashFunc(key: key)
|
||||
let bucket = buckets[index]
|
||||
// Traverse bucket, if key is found, return corresponding val
|
||||
for pair in bucket {
|
||||
if pair.key == key {
|
||||
return pair.val
|
||||
}
|
||||
}
|
||||
// Return nil if key not found
|
||||
return nil
|
||||
}
|
||||
|
||||
/* Add operation */
|
||||
func put(key: Int, val: String) {
|
||||
// When load factor exceeds threshold, perform expansion
|
||||
if loadFactor() > loadThres {
|
||||
extend()
|
||||
}
|
||||
let index = hashFunc(key: key)
|
||||
let bucket = buckets[index]
|
||||
// Traverse bucket, if specified key is encountered, update corresponding val and return
|
||||
for pair in bucket {
|
||||
if pair.key == key {
|
||||
pair.val = val
|
||||
return
|
||||
}
|
||||
}
|
||||
// If key does not exist, append key-value pair to the end
|
||||
let pair = Pair(key: key, val: val)
|
||||
buckets[index].append(pair)
|
||||
size += 1
|
||||
}
|
||||
|
||||
/* Remove operation */
|
||||
func remove(key: Int) {
|
||||
let index = hashFunc(key: key)
|
||||
let bucket = buckets[index]
|
||||
// Traverse bucket and remove key-value pair from it
|
||||
for (pairIndex, pair) in bucket.enumerated() {
|
||||
if pair.key == key {
|
||||
buckets[index].remove(at: pairIndex)
|
||||
size -= 1
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Expand hash table */
|
||||
func extend() {
|
||||
// Temporarily store the original hash table
|
||||
let bucketsTmp = buckets
|
||||
// Initialize expanded new hash table
|
||||
capacity *= extendRatio
|
||||
buckets = Array(repeating: [], count: capacity)
|
||||
size = 0
|
||||
// Move key-value pairs from original hash table to new hash table
|
||||
for bucket in bucketsTmp {
|
||||
for pair in bucket {
|
||||
put(key: pair.key, val: pair.val)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Print hash table */
|
||||
func print() {
|
||||
for bucket in buckets {
|
||||
let res = bucket.map { "\($0.key) -> \($0.val)" }
|
||||
Swift.print(res)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@main
|
||||
enum _HashMapChaining {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
/* Initialize hash table */
|
||||
let map = HashMapChaining()
|
||||
|
||||
/* Add operation */
|
||||
// Add key-value pair (key, value) to the hash table
|
||||
map.put(key: 12836, val: "Xiao Ha")
|
||||
map.put(key: 15937, val: "Xiao Luo")
|
||||
map.put(key: 16750, val: "Xiao Suan")
|
||||
map.put(key: 13276, val: "Xiao Fa")
|
||||
map.put(key: 10583, val: "Xiao Ya")
|
||||
print("\nAfter adding is complete, hash table is\nKey -> Value")
|
||||
map.print()
|
||||
|
||||
/* Query operation */
|
||||
// Input key into hash table to get value
|
||||
let name = map.get(key: 13276)
|
||||
print("\nInput student ID 13276, found name \(name!)")
|
||||
|
||||
/* Remove operation */
|
||||
// Remove key-value pair (key, value) from hash table
|
||||
map.remove(key: 12836)
|
||||
print("\nAfter removing 12836, hash table is\nKey -> Value")
|
||||
map.print()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
/**
|
||||
* File: hash_map_open_addressing.swift
|
||||
* Created Time: 2023-06-28
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
import utils
|
||||
|
||||
/* Hash table with open addressing */
|
||||
class HashMapOpenAddressing {
|
||||
var size: Int // Number of key-value pairs
|
||||
var capacity: Int // Hash table capacity
|
||||
var loadThres: Double // Load factor threshold for triggering expansion
|
||||
var extendRatio: Int // Expansion multiplier
|
||||
var buckets: [Pair?] // Bucket array
|
||||
var TOMBSTONE: Pair // Removal marker
|
||||
|
||||
/* Constructor */
|
||||
init() {
|
||||
size = 0
|
||||
capacity = 4
|
||||
loadThres = 2.0 / 3.0
|
||||
extendRatio = 2
|
||||
buckets = Array(repeating: nil, count: capacity)
|
||||
TOMBSTONE = Pair(key: -1, val: "-1")
|
||||
}
|
||||
|
||||
/* Hash function */
|
||||
func hashFunc(key: Int) -> Int {
|
||||
key % capacity
|
||||
}
|
||||
|
||||
/* Load factor */
|
||||
func loadFactor() -> Double {
|
||||
Double(size) / Double(capacity)
|
||||
}
|
||||
|
||||
/* Search for bucket index corresponding to key */
|
||||
func findBucket(key: Int) -> Int {
|
||||
var index = hashFunc(key: key)
|
||||
var firstTombstone = -1
|
||||
// Linear probing, break when encountering an empty bucket
|
||||
while buckets[index] != nil {
|
||||
// If key is encountered, return the corresponding bucket index
|
||||
if buckets[index]!.key == key {
|
||||
// If a removal marker was encountered before, move the key-value pair to that index
|
||||
if firstTombstone != -1 {
|
||||
buckets[firstTombstone] = buckets[index]
|
||||
buckets[index] = TOMBSTONE
|
||||
return firstTombstone // Return the moved bucket index
|
||||
}
|
||||
return index // Return bucket index
|
||||
}
|
||||
// Record the first removal marker encountered
|
||||
if firstTombstone == -1 && buckets[index] == TOMBSTONE {
|
||||
firstTombstone = index
|
||||
}
|
||||
// Calculate bucket index, wrap around to the head if past the tail
|
||||
index = (index + 1) % capacity
|
||||
}
|
||||
// If key does not exist, return the index for insertion
|
||||
return firstTombstone == -1 ? index : firstTombstone
|
||||
}
|
||||
|
||||
/* Query operation */
|
||||
func get(key: Int) -> String? {
|
||||
// Search for bucket index corresponding to key
|
||||
let index = findBucket(key: key)
|
||||
// If key-value pair is found, return corresponding val
|
||||
if buckets[index] != nil, buckets[index] != TOMBSTONE {
|
||||
return buckets[index]!.val
|
||||
}
|
||||
// If key-value pair does not exist, return null
|
||||
return nil
|
||||
}
|
||||
|
||||
/* Add operation */
|
||||
func put(key: Int, val: String) {
|
||||
// When load factor exceeds threshold, perform expansion
|
||||
if loadFactor() > loadThres {
|
||||
extend()
|
||||
}
|
||||
// Search for bucket index corresponding to key
|
||||
let index = findBucket(key: key)
|
||||
// If key-value pair is found, overwrite val and return
|
||||
if buckets[index] != nil, buckets[index] != TOMBSTONE {
|
||||
buckets[index]!.val = val
|
||||
return
|
||||
}
|
||||
// If key-value pair does not exist, add the key-value pair
|
||||
buckets[index] = Pair(key: key, val: val)
|
||||
size += 1
|
||||
}
|
||||
|
||||
/* Remove operation */
|
||||
func remove(key: Int) {
|
||||
// Search for bucket index corresponding to key
|
||||
let index = findBucket(key: key)
|
||||
// If key-value pair is found, overwrite it with removal marker
|
||||
if buckets[index] != nil, buckets[index] != TOMBSTONE {
|
||||
buckets[index] = TOMBSTONE
|
||||
size -= 1
|
||||
}
|
||||
}
|
||||
|
||||
/* Expand hash table */
|
||||
func extend() {
|
||||
// Temporarily store the original hash table
|
||||
let bucketsTmp = buckets
|
||||
// Initialize expanded new hash table
|
||||
capacity *= extendRatio
|
||||
buckets = Array(repeating: nil, count: capacity)
|
||||
size = 0
|
||||
// Move key-value pairs from original hash table to new hash table
|
||||
for pair in bucketsTmp {
|
||||
if let pair, pair != TOMBSTONE {
|
||||
put(key: pair.key, val: pair.val)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Print hash table */
|
||||
func print() {
|
||||
for pair in buckets {
|
||||
if pair == nil {
|
||||
Swift.print("null")
|
||||
} else if pair == TOMBSTONE {
|
||||
Swift.print("TOMBSTONE")
|
||||
} else {
|
||||
Swift.print("\(pair!.key) -> \(pair!.val)")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@main
|
||||
enum _HashMapOpenAddressing {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
/* Initialize hash table */
|
||||
let map = HashMapOpenAddressing()
|
||||
|
||||
/* Add operation */
|
||||
// Add key-value pair (key, value) to the hash table
|
||||
map.put(key: 12836, val: "Xiao Ha")
|
||||
map.put(key: 15937, val: "Xiao Luo")
|
||||
map.put(key: 16750, val: "Xiao Suan")
|
||||
map.put(key: 13276, val: "Xiao Fa")
|
||||
map.put(key: 10583, val: "Xiao Ya")
|
||||
print("\nAfter adding is complete, hash table is\nKey -> Value")
|
||||
map.print()
|
||||
|
||||
/* Query operation */
|
||||
// Input key into hash table to get value
|
||||
let name = map.get(key: 13276)
|
||||
print("\nInput student ID 13276, found name \(name!)")
|
||||
|
||||
/* Remove operation */
|
||||
// Remove key-value pair (key, value) from hash table
|
||||
map.remove(key: 16750)
|
||||
print("\nAfter removing 16750, hash table is\nKey -> Value")
|
||||
map.print()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* File: simple_hash.swift
|
||||
* Created Time: 2023-07-01
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Additive hash */
|
||||
func addHash(key: String) -> Int {
|
||||
var hash = 0
|
||||
let MODULUS = 1_000_000_007
|
||||
for c in key {
|
||||
for scalar in c.unicodeScalars {
|
||||
hash = (hash + Int(scalar.value)) % MODULUS
|
||||
}
|
||||
}
|
||||
return hash
|
||||
}
|
||||
|
||||
/* Multiplicative hash */
|
||||
func mulHash(key: String) -> Int {
|
||||
var hash = 0
|
||||
let MODULUS = 1_000_000_007
|
||||
for c in key {
|
||||
for scalar in c.unicodeScalars {
|
||||
hash = (31 * hash + Int(scalar.value)) % MODULUS
|
||||
}
|
||||
}
|
||||
return hash
|
||||
}
|
||||
|
||||
/* XOR hash */
|
||||
func xorHash(key: String) -> Int {
|
||||
var hash = 0
|
||||
let MODULUS = 1_000_000_007
|
||||
for c in key {
|
||||
for scalar in c.unicodeScalars {
|
||||
hash ^= Int(scalar.value)
|
||||
}
|
||||
}
|
||||
return hash & MODULUS
|
||||
}
|
||||
|
||||
/* Rotational hash */
|
||||
func rotHash(key: String) -> Int {
|
||||
var hash = 0
|
||||
let MODULUS = 1_000_000_007
|
||||
for c in key {
|
||||
for scalar in c.unicodeScalars {
|
||||
hash = ((hash << 4) ^ (hash >> 28) ^ Int(scalar.value)) % MODULUS
|
||||
}
|
||||
}
|
||||
return hash
|
||||
}
|
||||
|
||||
@main
|
||||
enum SimpleHash {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let key = "Hello Algo"
|
||||
|
||||
var hash = addHash(key: key)
|
||||
print("Additive hash value is \(hash)")
|
||||
|
||||
hash = mulHash(key: key)
|
||||
print("Multiplicative hash value is \(hash)")
|
||||
|
||||
hash = xorHash(key: key)
|
||||
print("XOR hash value is \(hash)")
|
||||
|
||||
hash = rotHash(key: key)
|
||||
print("Rotational hash value is \(hash)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* File: heap.swift
|
||||
* Created Time: 2024-03-17
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
import HeapModule
|
||||
import utils
|
||||
|
||||
func testPush(heap: inout Heap<Int>, val: Int) {
|
||||
heap.insert(val)
|
||||
print("\nAfter element \(val) pushes to heap\n")
|
||||
PrintUtil.printHeap(queue: heap.unordered)
|
||||
}
|
||||
|
||||
func testPop(heap: inout Heap<Int>) {
|
||||
let val = heap.removeMax()
|
||||
print("\nAfter heap top element \(val) pops from heap\n")
|
||||
PrintUtil.printHeap(queue: heap.unordered)
|
||||
}
|
||||
|
||||
@main
|
||||
enum _Heap {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
/* Initialize heap */
|
||||
// Swift's Heap type supports both max heap and min heap
|
||||
var heap = Heap<Int>()
|
||||
|
||||
/* Element enters heap */
|
||||
testPush(heap: &heap, val: 1)
|
||||
testPush(heap: &heap, val: 3)
|
||||
testPush(heap: &heap, val: 2)
|
||||
testPush(heap: &heap, val: 5)
|
||||
testPush(heap: &heap, val: 4)
|
||||
|
||||
/* Check if heap is empty */
|
||||
let peek = heap.max()
|
||||
print("\nHeap top element is \(peek!)\n")
|
||||
|
||||
/* Time complexity is O(n), not O(nlogn) */
|
||||
testPop(heap: &heap)
|
||||
testPop(heap: &heap)
|
||||
testPop(heap: &heap)
|
||||
testPop(heap: &heap)
|
||||
testPop(heap: &heap)
|
||||
|
||||
/* Get heap size */
|
||||
let size = heap.count
|
||||
print("\nHeap size is \(size)\n")
|
||||
|
||||
/* Check if heap is empty */
|
||||
let isEmpty = heap.isEmpty
|
||||
print("\nIs heap empty \(isEmpty)\n")
|
||||
|
||||
/* Input list and build heap */
|
||||
// Time complexity is O(n), not O(nlogn)
|
||||
let heap2 = Heap([1, 3, 2, 5, 4])
|
||||
print("\nAfter input list and build heap")
|
||||
PrintUtil.printHeap(queue: heap2.unordered)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
/**
|
||||
* File: my_heap.swift
|
||||
* Created Time: 2023-01-28
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
import utils
|
||||
|
||||
/* Max heap */
|
||||
class MaxHeap {
|
||||
private var maxHeap: [Int]
|
||||
|
||||
/* Constructor, build heap based on input list */
|
||||
init(nums: [Int]) {
|
||||
// Add list elements to heap as is
|
||||
maxHeap = nums
|
||||
// Heapify all nodes except leaf nodes
|
||||
for i in (0 ... parent(i: size() - 1)).reversed() {
|
||||
siftDown(i: i)
|
||||
}
|
||||
}
|
||||
|
||||
/* Get index of left child node */
|
||||
private func left(i: Int) -> Int {
|
||||
2 * i + 1
|
||||
}
|
||||
|
||||
/* Get index of right child node */
|
||||
private func right(i: Int) -> Int {
|
||||
2 * i + 2
|
||||
}
|
||||
|
||||
/* Get index of parent node */
|
||||
private func parent(i: Int) -> Int {
|
||||
(i - 1) / 2 // Floor division
|
||||
}
|
||||
|
||||
/* Swap elements */
|
||||
private func swap(i: Int, j: Int) {
|
||||
maxHeap.swapAt(i, j)
|
||||
}
|
||||
|
||||
/* Get heap size */
|
||||
func size() -> Int {
|
||||
maxHeap.count
|
||||
}
|
||||
|
||||
/* Check if heap is empty */
|
||||
func isEmpty() -> Bool {
|
||||
size() == 0
|
||||
}
|
||||
|
||||
/* Access top element */
|
||||
func peek() -> Int {
|
||||
maxHeap[0]
|
||||
}
|
||||
|
||||
/* Element enters heap */
|
||||
func push(val: Int) {
|
||||
// Add node
|
||||
maxHeap.append(val)
|
||||
// Heapify from bottom to top
|
||||
siftUp(i: size() - 1)
|
||||
}
|
||||
|
||||
/* Starting from node i, heapify from bottom to top */
|
||||
private func siftUp(i: Int) {
|
||||
var i = i
|
||||
while true {
|
||||
// Get parent node of node i
|
||||
let p = parent(i: i)
|
||||
// When "crossing root node" or "node needs no repair", end heapify
|
||||
if p < 0 || maxHeap[i] <= maxHeap[p] {
|
||||
break
|
||||
}
|
||||
// Swap two nodes
|
||||
swap(i: i, j: p)
|
||||
// Loop upward heapify
|
||||
i = p
|
||||
}
|
||||
}
|
||||
|
||||
/* Element exits heap */
|
||||
func pop() -> Int {
|
||||
// Handle empty case
|
||||
if isEmpty() {
|
||||
fatalError("Heap is empty")
|
||||
}
|
||||
// Delete node
|
||||
swap(i: 0, j: size() - 1)
|
||||
// Remove node
|
||||
let val = maxHeap.remove(at: size() - 1)
|
||||
// Return top element
|
||||
siftDown(i: 0)
|
||||
// Return heap top element
|
||||
return val
|
||||
}
|
||||
|
||||
/* Starting from node i, heapify from top to bottom */
|
||||
private func siftDown(i: Int) {
|
||||
var i = i
|
||||
while true {
|
||||
// If node i is largest or indices l, r are out of bounds, no need to continue heapify, break
|
||||
let l = left(i: i)
|
||||
let r = right(i: i)
|
||||
var ma = i
|
||||
if l < size(), maxHeap[l] > maxHeap[ma] {
|
||||
ma = l
|
||||
}
|
||||
if r < size(), maxHeap[r] > maxHeap[ma] {
|
||||
ma = r
|
||||
}
|
||||
// Swap two nodes
|
||||
if ma == i {
|
||||
break
|
||||
}
|
||||
// Swap two nodes
|
||||
swap(i: i, j: ma)
|
||||
// Loop downwards heapification
|
||||
i = ma
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
func print() {
|
||||
let queue = maxHeap
|
||||
PrintUtil.printHeap(queue: queue)
|
||||
}
|
||||
}
|
||||
|
||||
@main
|
||||
enum MyHeap {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
/* Consider negating the elements before entering the heap, which can reverse the size relationship, thus implementing max heap */
|
||||
let maxHeap = MaxHeap(nums: [9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2])
|
||||
print("\nAfter inputting list and building heap")
|
||||
maxHeap.print()
|
||||
|
||||
/* Check if heap is empty */
|
||||
var peek = maxHeap.peek()
|
||||
print("\nHeap top element is \(peek)")
|
||||
|
||||
/* Element enters heap */
|
||||
let val = 7
|
||||
maxHeap.push(val: val)
|
||||
print("\nAfter element \(val) pushes to heap")
|
||||
maxHeap.print()
|
||||
|
||||
/* Time complexity is O(n), not O(nlogn) */
|
||||
peek = maxHeap.pop()
|
||||
print("\nAfter heap top element \(peek) pops from heap")
|
||||
maxHeap.print()
|
||||
|
||||
/* Get heap size */
|
||||
let size = maxHeap.size()
|
||||
print("\nHeap size is \(size)")
|
||||
|
||||
/* Check if heap is empty */
|
||||
let isEmpty = maxHeap.isEmpty()
|
||||
print("\nIs heap empty \(isEmpty)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* File: top_k.swift
|
||||
* Created Time: 2023-07-02
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
import HeapModule
|
||||
import utils
|
||||
|
||||
/* Find the largest k elements in array based on heap */
|
||||
func topKHeap(nums: [Int], k: Int) -> [Int] {
|
||||
// Initialize min heap and build heap with first k elements
|
||||
var heap = Heap(nums.prefix(k))
|
||||
// Starting from the (k+1)th element, maintain heap length as k
|
||||
for i in nums.indices.dropFirst(k) {
|
||||
// If current element is greater than top element, top element exits heap, current element enters heap
|
||||
if nums[i] > heap.min()! {
|
||||
_ = heap.removeMin()
|
||||
heap.insert(nums[i])
|
||||
}
|
||||
}
|
||||
return heap.unordered
|
||||
}
|
||||
|
||||
@main
|
||||
enum TopK {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let nums = [1, 7, 6, 3, 2]
|
||||
let k = 3
|
||||
|
||||
let res = topKHeap(nums: nums, k: k)
|
||||
print("The largest \(k) elements are")
|
||||
PrintUtil.printHeap(queue: res)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* File: binary_search.swift
|
||||
* Created Time: 2023-01-28
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Binary search (closed interval on both sides) */
|
||||
func binarySearch(nums: [Int], target: Int) -> Int {
|
||||
// Initialize closed interval [0, n-1], i.e., i, j point to the first and last elements of the array
|
||||
var i = nums.startIndex
|
||||
var j = nums.endIndex - 1
|
||||
// Loop, exit when the search interval is empty (empty when i > j)
|
||||
while i <= j {
|
||||
let m = i + (j - i) / 2 // Calculate the midpoint index m
|
||||
if nums[m] < target { // This means target is in the interval [m+1, j]
|
||||
i = m + 1
|
||||
} else if nums[m] > target { // This means target is in the interval [i, m-1]
|
||||
j = m - 1
|
||||
} else { // Found the target element, return its index
|
||||
return m
|
||||
}
|
||||
}
|
||||
// Target element not found, return -1
|
||||
return -1
|
||||
}
|
||||
|
||||
/* Binary search (left-closed right-open interval) */
|
||||
func binarySearchLCRO(nums: [Int], target: Int) -> Int {
|
||||
// Initialize left-closed right-open interval [0, n), i.e., i, j point to the first element and last element+1
|
||||
var i = nums.startIndex
|
||||
var j = nums.endIndex
|
||||
// Loop, exit when the search interval is empty (empty when i = j)
|
||||
while i < j {
|
||||
let m = i + (j - i) / 2 // Calculate the midpoint index m
|
||||
if nums[m] < target { // This means target is in the interval [m+1, j)
|
||||
i = m + 1
|
||||
} else if nums[m] > target { // This means target is in the interval [i, m)
|
||||
j = m
|
||||
} else { // Found the target element, return its index
|
||||
return m
|
||||
}
|
||||
}
|
||||
// Target element not found, return -1
|
||||
return -1
|
||||
}
|
||||
|
||||
@main
|
||||
enum BinarySearch {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let target = 6
|
||||
let nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35]
|
||||
|
||||
/* Binary search (closed interval on both sides) */
|
||||
var index = binarySearch(nums: nums, target: target)
|
||||
print("Index of target element 6 = \(index)")
|
||||
|
||||
/* Binary search (left-closed right-open interval) */
|
||||
index = binarySearchLCRO(nums: nums, target: target)
|
||||
print("Index of target element 6 = \(index)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* File: binary_search_edge.swift
|
||||
* Created Time: 2023-08-06
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
import binary_search_insertion_target
|
||||
|
||||
/* Binary search for the leftmost target */
|
||||
func binarySearchLeftEdge(nums: [Int], target: Int) -> Int {
|
||||
// Equivalent to finding the insertion point of target
|
||||
let i = binarySearchInsertion(nums: nums, target: target)
|
||||
// Target not found, return -1
|
||||
if i == nums.endIndex || nums[i] != target {
|
||||
return -1
|
||||
}
|
||||
// Found target, return index i
|
||||
return i
|
||||
}
|
||||
|
||||
/* Binary search for the rightmost target */
|
||||
func binarySearchRightEdge(nums: [Int], target: Int) -> Int {
|
||||
// Convert to finding the leftmost target + 1
|
||||
let i = binarySearchInsertion(nums: nums, target: target + 1)
|
||||
// j points to the rightmost target, i points to the first element greater than target
|
||||
let j = i - 1
|
||||
// Target not found, return -1
|
||||
if j == -1 || nums[j] != target {
|
||||
return -1
|
||||
}
|
||||
// Found target, return index j
|
||||
return j
|
||||
}
|
||||
|
||||
@main
|
||||
enum BinarySearchEdge {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
// Array with duplicate elements
|
||||
let nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15]
|
||||
print("\nArray nums = \(nums)")
|
||||
|
||||
// Binary search left and right boundaries
|
||||
for target in [6, 7] {
|
||||
var index = binarySearchLeftEdge(nums: nums, target: target)
|
||||
print("Leftmost element \(target) index is \(index)")
|
||||
index = binarySearchRightEdge(nums: nums, target: target)
|
||||
print("Rightmost element \(target) index is \(index)")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* File: binary_search_insertion.swift
|
||||
* Created Time: 2023-08-06
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Binary search for insertion point (no duplicate elements) */
|
||||
func binarySearchInsertionSimple(nums: [Int], target: Int) -> Int {
|
||||
// Initialize closed interval [0, n-1]
|
||||
var i = nums.startIndex
|
||||
var j = nums.endIndex - 1
|
||||
while i <= j {
|
||||
let m = i + (j - i) / 2 // Calculate the midpoint index m
|
||||
if nums[m] < target {
|
||||
i = m + 1 // target is in the interval [m+1, j]
|
||||
} else if nums[m] > target {
|
||||
j = m - 1 // target is in the interval [i, m-1]
|
||||
} else {
|
||||
return m // Found target, return insertion point m
|
||||
}
|
||||
}
|
||||
// Target not found, return insertion point i
|
||||
return i
|
||||
}
|
||||
|
||||
/* Binary search for insertion point (with duplicate elements) */
|
||||
public func binarySearchInsertion(nums: [Int], target: Int) -> Int {
|
||||
// Initialize closed interval [0, n-1]
|
||||
var i = nums.startIndex
|
||||
var j = nums.endIndex - 1
|
||||
while i <= j {
|
||||
let m = i + (j - i) / 2 // Calculate the midpoint index m
|
||||
if nums[m] < target {
|
||||
i = m + 1 // target is in the interval [m+1, j]
|
||||
} else if nums[m] > target {
|
||||
j = m - 1 // target is in the interval [i, m-1]
|
||||
} else {
|
||||
j = m - 1 // The first element less than target is in the interval [i, m-1]
|
||||
}
|
||||
}
|
||||
// Return insertion point i
|
||||
return i
|
||||
}
|
||||
|
||||
#if !TARGET
|
||||
|
||||
@main
|
||||
enum BinarySearchInsertion {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
// Array without duplicate elements
|
||||
var nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35]
|
||||
print("\nArray nums = \(nums)")
|
||||
// Binary search for insertion point
|
||||
for target in [6, 9] {
|
||||
let index = binarySearchInsertionSimple(nums: nums, target: target)
|
||||
print("Insertion point index for element \(target) is \(index)")
|
||||
}
|
||||
|
||||
// Array with duplicate elements
|
||||
nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15]
|
||||
print("\nArray nums = \(nums)")
|
||||
// Binary search for insertion point
|
||||
for target in [2, 6, 20] {
|
||||
let index = binarySearchInsertion(nums: nums, target: target)
|
||||
print("Insertion point index for element \(target) is \(index)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* File: binary_search_insertion.swift
|
||||
* Created Time: 2023-08-06
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Binary search for insertion point (no duplicate elements) */
|
||||
func binarySearchInsertionSimple(nums: [Int], target: Int) -> Int {
|
||||
// Initialize closed interval [0, n-1]
|
||||
var i = nums.startIndex
|
||||
var j = nums.endIndex - 1
|
||||
while i <= j {
|
||||
let m = i + (j - i) / 2 // Calculate the midpoint index m
|
||||
if nums[m] < target {
|
||||
i = m + 1 // target is in the interval [m+1, j]
|
||||
} else if nums[m] > target {
|
||||
j = m - 1 // target is in the interval [i, m-1]
|
||||
} else {
|
||||
return m // Found target, return insertion point m
|
||||
}
|
||||
}
|
||||
// Target not found, return insertion point i
|
||||
return i
|
||||
}
|
||||
|
||||
/* Binary search for insertion point (with duplicate elements) */
|
||||
public func binarySearchInsertion(nums: [Int], target: Int) -> Int {
|
||||
// Initialize closed interval [0, n-1]
|
||||
var i = nums.startIndex
|
||||
var j = nums.endIndex - 1
|
||||
while i <= j {
|
||||
let m = i + (j - i) / 2 // Calculate the midpoint index m
|
||||
if nums[m] < target {
|
||||
i = m + 1 // target is in the interval [m+1, j]
|
||||
} else if nums[m] > target {
|
||||
j = m - 1 // target is in the interval [i, m-1]
|
||||
} else {
|
||||
j = m - 1 // The first element less than target is in the interval [i, m-1]
|
||||
}
|
||||
}
|
||||
// Return insertion point i
|
||||
return i
|
||||
}
|
||||
|
||||
#if !TARGET
|
||||
|
||||
@main
|
||||
enum BinarySearchInsertion {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
// Array without duplicate elements
|
||||
var nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35]
|
||||
print("\nArray nums = \(nums)")
|
||||
// Binary search for insertion point
|
||||
for target in [6, 9] {
|
||||
let index = binarySearchInsertionSimple(nums: nums, target: target)
|
||||
print("Insertion point index for element \(target) is \(index)")
|
||||
}
|
||||
|
||||
// Array with duplicate elements
|
||||
nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15]
|
||||
print("\nArray nums = \(nums)")
|
||||
// Binary search for insertion point
|
||||
for target in [2, 6, 20] {
|
||||
let index = binarySearchInsertion(nums: nums, target: target)
|
||||
print("Insertion point index for element \(target) is \(index)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* File: hashing_search.swift
|
||||
* Created Time: 2023-01-28
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
import utils
|
||||
|
||||
/* Hash search (array) */
|
||||
func hashingSearchArray(map: [Int: Int], target: Int) -> Int {
|
||||
// Hash table's key: target element, value: index
|
||||
// If this key does not exist in the hash table, return -1
|
||||
return map[target, default: -1]
|
||||
}
|
||||
|
||||
/* Hash search (linked list) */
|
||||
func hashingSearchLinkedList(map: [Int: ListNode], target: Int) -> ListNode? {
|
||||
// Hash table key: target node value, value: node object
|
||||
// If key is not in hash table, return null
|
||||
return map[target]
|
||||
}
|
||||
|
||||
@main
|
||||
enum HashingSearch {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let target = 3
|
||||
|
||||
/* Hash search (array) */
|
||||
let nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8]
|
||||
// Initialize hash table
|
||||
var map: [Int: Int] = [:]
|
||||
for i in nums.indices {
|
||||
map[nums[i]] = i // key: element, value: index
|
||||
}
|
||||
let index = hashingSearchArray(map: map, target: target)
|
||||
print("Index of target element 3 = \(index)")
|
||||
|
||||
/* Hash search (linked list) */
|
||||
var head = ListNode.arrToLinkedList(arr: nums)
|
||||
// Initialize hash table
|
||||
var map1: [Int: ListNode] = [:]
|
||||
while head != nil {
|
||||
map1[head!.val] = head! // key: node value, value: node
|
||||
head = head?.next
|
||||
}
|
||||
let node = hashingSearchLinkedList(map: map1, target: target)
|
||||
print("Node object corresponding to target node value 3 is \(node!)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* File: linear_search.swift
|
||||
* Created Time: 2023-01-28
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
import utils
|
||||
|
||||
/* Linear search (array) */
|
||||
func linearSearchArray(nums: [Int], target: Int) -> Int {
|
||||
// Traverse array
|
||||
for i in nums.indices {
|
||||
// Found the target element, return its index
|
||||
if nums[i] == target {
|
||||
return i
|
||||
}
|
||||
}
|
||||
// Target element not found, return -1
|
||||
return -1
|
||||
}
|
||||
|
||||
/* Linear search (linked list) */
|
||||
func linearSearchLinkedList(head: ListNode?, target: Int) -> ListNode? {
|
||||
var head = head
|
||||
// Traverse the linked list
|
||||
while head != nil {
|
||||
// Found the target node, return it
|
||||
if head?.val == target {
|
||||
return head
|
||||
}
|
||||
head = head?.next
|
||||
}
|
||||
// Target node not found, return null
|
||||
return nil
|
||||
}
|
||||
|
||||
@main
|
||||
enum LinearSearch {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let target = 3
|
||||
|
||||
/* Perform linear search in array */
|
||||
let nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8]
|
||||
let index = linearSearchArray(nums: nums, target: target)
|
||||
print("Index of target element 3 = \(index)")
|
||||
|
||||
/* Perform linear search in linked list */
|
||||
let head = ListNode.arrToLinkedList(arr: nums)
|
||||
let node = linearSearchLinkedList(head: head, target: target)
|
||||
print("Node object corresponding to target node value 3 is \(node!)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* File: two_sum.swift
|
||||
* Created Time: 2023-01-03
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Method 1: Brute force enumeration */
|
||||
func twoSumBruteForce(nums: [Int], target: Int) -> [Int] {
|
||||
// Two nested loops, time complexity is O(n^2)
|
||||
for i in nums.indices.dropLast() {
|
||||
for j in nums.indices.dropFirst(i + 1) {
|
||||
if nums[i] + nums[j] == target {
|
||||
return [i, j]
|
||||
}
|
||||
}
|
||||
}
|
||||
return [0]
|
||||
}
|
||||
|
||||
/* Method 2: Auxiliary hash table */
|
||||
func twoSumHashTable(nums: [Int], target: Int) -> [Int] {
|
||||
// Auxiliary hash table, space complexity is O(n)
|
||||
var dic: [Int: Int] = [:]
|
||||
// Single loop, time complexity is O(n)
|
||||
for i in nums.indices {
|
||||
if let j = dic[target - nums[i]] {
|
||||
return [j, i]
|
||||
}
|
||||
dic[nums[i]] = i
|
||||
}
|
||||
return [0]
|
||||
}
|
||||
|
||||
@main
|
||||
enum LeetcodeTwoSum {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
// ======= Test Case =======
|
||||
let nums = [2, 7, 11, 15]
|
||||
let target = 13
|
||||
// ====== Driver Code ======
|
||||
// Method 1
|
||||
var res = twoSumBruteForce(nums: nums, target: target)
|
||||
print("Method 1 res = \(res)")
|
||||
// Method 2
|
||||
res = twoSumHashTable(nums: nums, target: target)
|
||||
print("Method 2 res = \(res)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* File: bubble_sort.swift
|
||||
* Created Time: 2023-01-29
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Bubble sort */
|
||||
func bubbleSort(nums: inout [Int]) {
|
||||
// Outer loop: unsorted range is [0, i]
|
||||
for i in nums.indices.dropFirst().reversed() {
|
||||
// Inner loop: swap the largest element in the unsorted range [0, i] to the rightmost end of that range
|
||||
for j in 0 ..< i {
|
||||
if nums[j] > nums[j + 1] {
|
||||
// Swap nums[j] and nums[j + 1]
|
||||
nums.swapAt(j, j + 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Bubble sort (flag optimization) */
|
||||
func bubbleSortWithFlag(nums: inout [Int]) {
|
||||
// Outer loop: unsorted range is [0, i]
|
||||
for i in nums.indices.dropFirst().reversed() {
|
||||
var flag = false // Initialize flag
|
||||
for j in 0 ..< i {
|
||||
if nums[j] > nums[j + 1] {
|
||||
// Swap nums[j] and nums[j + 1]
|
||||
nums.swapAt(j, j + 1)
|
||||
flag = true // Record element swap
|
||||
}
|
||||
}
|
||||
if !flag { // No elements were swapped in this round of "bubbling", exit directly
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@main
|
||||
enum BubbleSort {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
var nums = [4, 1, 3, 1, 5, 2]
|
||||
bubbleSort(nums: &nums)
|
||||
print("After bubble sort, nums = \(nums)")
|
||||
|
||||
var nums1 = [4, 1, 3, 1, 5, 2]
|
||||
bubbleSortWithFlag(nums: &nums1)
|
||||
print("After bubble sort, nums1 = \(nums1)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* File: bucket_sort.swift
|
||||
* Created Time: 2023-03-27
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Bucket sort */
|
||||
func bucketSort(nums: inout [Double]) {
|
||||
// Initialize k = n/2 buckets, expected to allocate 2 elements per bucket
|
||||
let k = nums.count / 2
|
||||
var buckets = (0 ..< k).map { _ in [Double]() }
|
||||
// 1. Distribute array elements into various buckets
|
||||
for num in nums {
|
||||
// Input data range is [0, 1), use num * k to map to index range [0, k-1]
|
||||
let i = Int(num * Double(k))
|
||||
// Add num to bucket i
|
||||
buckets[i].append(num)
|
||||
}
|
||||
// 2. Sort each bucket
|
||||
for i in buckets.indices {
|
||||
// Use built-in sorting function, can also replace with other sorting algorithms
|
||||
buckets[i].sort()
|
||||
}
|
||||
// 3. Traverse buckets to merge results
|
||||
var i = nums.startIndex
|
||||
for bucket in buckets {
|
||||
for num in bucket {
|
||||
nums[i] = num
|
||||
i += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@main
|
||||
enum BucketSort {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
// Assume input data is floating point, interval [0, 1)
|
||||
var nums = [0.49, 0.96, 0.82, 0.09, 0.57, 0.43, 0.91, 0.75, 0.15, 0.37]
|
||||
bucketSort(nums: &nums)
|
||||
print("After bucket sort, nums = \(nums)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* File: counting_sort.swift
|
||||
* Created Time: 2023-03-22
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Counting sort */
|
||||
// Simple implementation, cannot be used for sorting objects
|
||||
func countingSortNaive(nums: inout [Int]) {
|
||||
// 1. Count the maximum element m in the array
|
||||
let m = nums.max()!
|
||||
// 2. Count the occurrence of each number
|
||||
// counter[num] represents the occurrence of num
|
||||
var counter = Array(repeating: 0, count: m + 1)
|
||||
for num in nums {
|
||||
counter[num] += 1
|
||||
}
|
||||
// 3. Traverse counter, filling each element back into the original array nums
|
||||
var i = 0
|
||||
for num in 0 ..< m + 1 {
|
||||
for _ in 0 ..< counter[num] {
|
||||
nums[i] = num
|
||||
i += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Counting sort */
|
||||
// Complete implementation, can sort objects and is a stable sort
|
||||
func countingSort(nums: inout [Int]) {
|
||||
// 1. Count the maximum element m in the array
|
||||
let m = nums.max()!
|
||||
// 2. Count the occurrence of each number
|
||||
// counter[num] represents the occurrence of num
|
||||
var counter = Array(repeating: 0, count: m + 1)
|
||||
for num in nums {
|
||||
counter[num] += 1
|
||||
}
|
||||
// 3. Calculate the prefix sum of counter, converting "occurrence count" to "tail index"
|
||||
// counter[num]-1 is the last index where num appears in res
|
||||
for i in 0 ..< m {
|
||||
counter[i + 1] += counter[i]
|
||||
}
|
||||
// 4. Traverse nums in reverse order, placing each element into the result array res
|
||||
// Initialize the array res to record results
|
||||
var res = Array(repeating: 0, count: nums.count)
|
||||
for i in nums.indices.reversed() {
|
||||
let num = nums[i]
|
||||
res[counter[num] - 1] = num // Place num at the corresponding index
|
||||
counter[num] -= 1 // Decrement the prefix sum by 1, getting the next index to place num
|
||||
}
|
||||
// Use result array res to overwrite the original array nums
|
||||
for i in nums.indices {
|
||||
nums[i] = res[i]
|
||||
}
|
||||
}
|
||||
|
||||
@main
|
||||
enum CountingSort {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
var nums = [1, 0, 1, 2, 0, 4, 0, 2, 2, 4]
|
||||
countingSortNaive(nums: &nums)
|
||||
print("After counting sort (cannot sort objects), nums = \(nums)")
|
||||
|
||||
var nums1 = [1, 0, 1, 2, 0, 4, 0, 2, 2, 4]
|
||||
countingSort(nums: &nums1)
|
||||
print("After counting sort, nums1 = \(nums1)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* File: heap_sort.swift
|
||||
* Created Time: 2023-05-28
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Heap length is n, start heapifying node i, from top to bottom */
|
||||
func siftDown(nums: inout [Int], n: Int, i: Int) {
|
||||
var i = i
|
||||
while true {
|
||||
// If node i is largest or indices l, r are out of bounds, no need to continue heapify, break
|
||||
let l = 2 * i + 1
|
||||
let r = 2 * i + 2
|
||||
var ma = i
|
||||
if l < n, nums[l] > nums[ma] {
|
||||
ma = l
|
||||
}
|
||||
if r < n, nums[r] > nums[ma] {
|
||||
ma = r
|
||||
}
|
||||
// Swap two nodes
|
||||
if ma == i {
|
||||
break
|
||||
}
|
||||
// Swap two nodes
|
||||
nums.swapAt(i, ma)
|
||||
// Loop downwards heapification
|
||||
i = ma
|
||||
}
|
||||
}
|
||||
|
||||
/* Heap sort */
|
||||
func heapSort(nums: inout [Int]) {
|
||||
// Build heap operation: heapify all nodes except leaves
|
||||
for i in stride(from: nums.count / 2 - 1, through: 0, by: -1) {
|
||||
siftDown(nums: &nums, n: nums.count, i: i)
|
||||
}
|
||||
// Extract the largest element from the heap and repeat for n-1 rounds
|
||||
for i in nums.indices.dropFirst().reversed() {
|
||||
// Delete node
|
||||
nums.swapAt(0, i)
|
||||
// Start heapifying the root node, from top to bottom
|
||||
siftDown(nums: &nums, n: i, i: 0)
|
||||
}
|
||||
}
|
||||
|
||||
@main
|
||||
enum HeapSort {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
var nums = [4, 1, 3, 1, 5, 2]
|
||||
heapSort(nums: &nums)
|
||||
print("After heap sort, nums = \(nums)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* File: insertion_sort.swift
|
||||
* Created Time: 2023-01-29
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Insertion sort */
|
||||
func insertionSort(nums: inout [Int]) {
|
||||
// Outer loop: sorted interval is [0, i-1]
|
||||
for i in nums.indices.dropFirst() {
|
||||
let base = nums[i]
|
||||
var j = i - 1
|
||||
// Inner loop: insert base into the correct position within the sorted interval [0, i-1]
|
||||
while j >= 0, nums[j] > base {
|
||||
nums[j + 1] = nums[j] // Move nums[j] to the right by one position
|
||||
j -= 1
|
||||
}
|
||||
nums[j + 1] = base // Assign base to the correct position
|
||||
}
|
||||
}
|
||||
|
||||
@main
|
||||
enum InsertionSort {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
var nums = [4, 1, 3, 1, 5, 2]
|
||||
insertionSort(nums: &nums)
|
||||
print("After insertion sort, nums = \(nums)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* File: merge_sort.swift
|
||||
* Created Time: 2023-01-29
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Merge left subarray and right subarray */
|
||||
func merge(nums: inout [Int], left: Int, mid: Int, right: Int) {
|
||||
// Left subarray interval is [left, mid], right subarray interval is [mid+1, right]
|
||||
// Create a temporary array tmp to store the merged results
|
||||
var tmp = Array(repeating: 0, count: right - left + 1)
|
||||
// Initialize the start indices of the left and right subarrays
|
||||
var i = left, j = mid + 1, k = 0
|
||||
// While both subarrays still have elements, compare and copy the smaller element into the temporary array
|
||||
while i <= mid, j <= right {
|
||||
if nums[i] <= nums[j] {
|
||||
tmp[k] = nums[i]
|
||||
i += 1
|
||||
} else {
|
||||
tmp[k] = nums[j]
|
||||
j += 1
|
||||
}
|
||||
k += 1
|
||||
}
|
||||
// Copy the remaining elements of the left and right subarrays into the temporary array
|
||||
while i <= mid {
|
||||
tmp[k] = nums[i]
|
||||
i += 1
|
||||
k += 1
|
||||
}
|
||||
while j <= right {
|
||||
tmp[k] = nums[j]
|
||||
j += 1
|
||||
k += 1
|
||||
}
|
||||
// Copy the elements from the temporary array tmp back to the original array nums at the corresponding interval
|
||||
for k in tmp.indices {
|
||||
nums[left + k] = tmp[k]
|
||||
}
|
||||
}
|
||||
|
||||
/* Merge sort */
|
||||
func mergeSort(nums: inout [Int], left: Int, right: Int) {
|
||||
// Termination condition
|
||||
if left >= right { // Terminate recursion when subarray length is 1
|
||||
return
|
||||
}
|
||||
// Divide and conquer stage
|
||||
let mid = left + (right - left) / 2 // Calculate midpoint
|
||||
mergeSort(nums: &nums, left: left, right: mid) // Recursively process the left subarray
|
||||
mergeSort(nums: &nums, left: mid + 1, right: right) // Recursively process the right subarray
|
||||
// Merge stage
|
||||
merge(nums: &nums, left: left, mid: mid, right: right)
|
||||
}
|
||||
|
||||
@main
|
||||
enum MergeSort {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
/* Merge sort */
|
||||
var nums = [7, 3, 2, 6, 0, 1, 5, 4]
|
||||
mergeSort(nums: &nums, left: nums.startIndex, right: nums.endIndex - 1)
|
||||
print("After merge sort, nums = \(nums)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* File: quick_sort.swift
|
||||
* Created Time: 2023-01-29
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Quick sort class */
|
||||
/* Sentinel partition */
|
||||
func partition(nums: inout [Int], left: Int, right: Int) -> Int {
|
||||
// Use nums[left] as the pivot
|
||||
var i = left
|
||||
var j = right
|
||||
while i < j {
|
||||
while i < j, nums[j] >= nums[left] {
|
||||
j -= 1 // Search from right to left for the first element smaller than the pivot
|
||||
}
|
||||
while i < j, nums[i] <= nums[left] {
|
||||
i += 1 // Search from left to right for the first element greater than the pivot
|
||||
}
|
||||
nums.swapAt(i, j) // Swap these two elements
|
||||
}
|
||||
nums.swapAt(i, left) // Swap the pivot to the boundary between the two subarrays
|
||||
return i // Return the index of the pivot
|
||||
}
|
||||
|
||||
/* Quick sort */
|
||||
func quickSort(nums: inout [Int], left: Int, right: Int) {
|
||||
// Terminate recursion when subarray length is 1
|
||||
if left >= right {
|
||||
return
|
||||
}
|
||||
// Sentinel partition
|
||||
let pivot = partition(nums: &nums, left: left, right: right)
|
||||
// Recursively process the left subarray and right subarray
|
||||
quickSort(nums: &nums, left: left, right: pivot - 1)
|
||||
quickSort(nums: &nums, left: pivot + 1, right: right)
|
||||
}
|
||||
|
||||
/* Quick sort class (median pivot optimization) */
|
||||
/* Select the median of three candidate elements */
|
||||
func medianThree(nums: [Int], left: Int, mid: Int, right: Int) -> Int {
|
||||
let l = nums[left]
|
||||
let m = nums[mid]
|
||||
let r = nums[right]
|
||||
if (l <= m && m <= r) || (r <= m && m <= l) {
|
||||
return mid // m is between l and r
|
||||
}
|
||||
if (m <= l && l <= r) || (r <= l && l <= m) {
|
||||
return left // l is between m and r
|
||||
}
|
||||
return right
|
||||
}
|
||||
|
||||
/* Sentinel partition (median of three) */
|
||||
func partitionMedian(nums: inout [Int], left: Int, right: Int) -> Int {
|
||||
// Select the median of three candidate elements
|
||||
let med = medianThree(nums: nums, left: left, mid: left + (right - left) / 2, right: right)
|
||||
// Swap the median to the array's leftmost position
|
||||
nums.swapAt(left, med)
|
||||
return partition(nums: &nums, left: left, right: right)
|
||||
}
|
||||
|
||||
/* Quick sort (recursion depth optimization) */
|
||||
func quickSortMedian(nums: inout [Int], left: Int, right: Int) {
|
||||
// Terminate recursion when subarray length is 1
|
||||
if left >= right {
|
||||
return
|
||||
}
|
||||
// Sentinel partition
|
||||
let pivot = partitionMedian(nums: &nums, left: left, right: right)
|
||||
// Recursively process the left subarray and right subarray
|
||||
quickSortMedian(nums: &nums, left: left, right: pivot - 1)
|
||||
quickSortMedian(nums: &nums, left: pivot + 1, right: right)
|
||||
}
|
||||
|
||||
/* Quick sort (recursion depth optimization) */
|
||||
func quickSortTailCall(nums: inout [Int], left: Int, right: Int) {
|
||||
var left = left
|
||||
var right = right
|
||||
// Terminate when subarray length is 1
|
||||
while left < right {
|
||||
// Sentinel partition operation
|
||||
let pivot = partition(nums: &nums, left: left, right: right)
|
||||
// Perform quick sort on the shorter of the two subarrays
|
||||
if (pivot - left) < (right - pivot) {
|
||||
quickSortTailCall(nums: &nums, left: left, right: pivot - 1) // Recursively sort the left subarray
|
||||
left = pivot + 1 // Remaining unsorted interval is [pivot + 1, right]
|
||||
} else {
|
||||
quickSortTailCall(nums: &nums, left: pivot + 1, right: right) // Recursively sort the right subarray
|
||||
right = pivot - 1 // Remaining unsorted interval is [left, pivot - 1]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@main
|
||||
enum QuickSort {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
/* Quick sort */
|
||||
var nums = [2, 4, 1, 0, 3, 5]
|
||||
quickSort(nums: &nums, left: nums.startIndex, right: nums.endIndex - 1)
|
||||
print("After quick sort, nums = \(nums)")
|
||||
|
||||
/* Quick sort (recursion depth optimization) */
|
||||
var nums1 = [2, 4, 1, 0, 3, 5]
|
||||
quickSortMedian(nums: &nums1, left: nums1.startIndex, right: nums1.endIndex - 1)
|
||||
print("After quick sort (median pivot optimization), nums1 = \(nums1)")
|
||||
|
||||
/* Quick sort (recursion depth optimization) */
|
||||
var nums2 = [2, 4, 1, 0, 3, 5]
|
||||
quickSortTailCall(nums: &nums2, left: nums2.startIndex, right: nums2.endIndex - 1)
|
||||
print("After quick sort (recursion depth optimization), nums2 = \(nums2)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* File: radix_sort.swift
|
||||
* Created Time: 2023-01-29
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Get the k-th digit of element num, where exp = 10^(k-1) */
|
||||
func digit(num: Int, exp: Int) -> Int {
|
||||
// Passing exp instead of k can avoid repeated expensive exponentiation here
|
||||
(num / exp) % 10
|
||||
}
|
||||
|
||||
/* Counting sort (based on nums k-th digit) */
|
||||
func countingSortDigit(nums: inout [Int], exp: Int) {
|
||||
// Decimal digit range is 0~9, therefore need a bucket array of length 10
|
||||
var counter = Array(repeating: 0, count: 10)
|
||||
// Count the occurrence of digits 0~9
|
||||
for i in nums.indices {
|
||||
let d = digit(num: nums[i], exp: exp) // Get the k-th digit of nums[i], noted as d
|
||||
counter[d] += 1 // Count the occurrence of digit d
|
||||
}
|
||||
// Calculate prefix sum, converting "occurrence count" into "array index"
|
||||
for i in 1 ..< 10 {
|
||||
counter[i] += counter[i - 1]
|
||||
}
|
||||
// Traverse in reverse, based on bucket statistics, place each element into res
|
||||
var res = Array(repeating: 0, count: nums.count)
|
||||
for i in nums.indices.reversed() {
|
||||
let d = digit(num: nums[i], exp: exp)
|
||||
let j = counter[d] - 1 // Get the index j for d in the array
|
||||
res[j] = nums[i] // Place the current element at index j
|
||||
counter[d] -= 1 // Decrease the count of d by 1
|
||||
}
|
||||
// Use result to overwrite the original array nums
|
||||
for i in nums.indices {
|
||||
nums[i] = res[i]
|
||||
}
|
||||
}
|
||||
|
||||
/* Radix sort */
|
||||
func radixSort(nums: inout [Int]) {
|
||||
// Get the maximum element of the array, used to determine the maximum number of digits
|
||||
var m = Int.min
|
||||
for num in nums {
|
||||
if num > m {
|
||||
m = num
|
||||
}
|
||||
}
|
||||
// Traverse from the lowest to the highest digit
|
||||
for exp in sequence(first: 1, next: { m >= ($0 * 10) ? $0 * 10 : nil }) {
|
||||
// Perform counting sort on the k-th digit of array elements
|
||||
// k = 1 -> exp = 1
|
||||
// k = 2 -> exp = 10
|
||||
// i.e., exp = 10^(k-1)
|
||||
countingSortDigit(nums: &nums, exp: exp)
|
||||
}
|
||||
}
|
||||
|
||||
@main
|
||||
enum RadixSort {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
// Radix sort
|
||||
var nums = [
|
||||
10_546_151,
|
||||
35_663_510,
|
||||
42_865_989,
|
||||
34_862_445,
|
||||
81_883_077,
|
||||
88_906_420,
|
||||
72_429_244,
|
||||
30_524_779,
|
||||
82_060_337,
|
||||
63_832_996,
|
||||
]
|
||||
radixSort(nums: &nums)
|
||||
print("After radix sort, nums = \(nums)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* File: selection_sort.swift
|
||||
* Created Time: 2023-05-28
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Selection sort */
|
||||
func selectionSort(nums: inout [Int]) {
|
||||
// Outer loop: unsorted interval is [i, n-1]
|
||||
for i in nums.indices.dropLast() {
|
||||
// Inner loop: find the smallest element within the unsorted interval
|
||||
var k = i
|
||||
for j in nums.indices.dropFirst(i + 1) {
|
||||
if nums[j] < nums[k] {
|
||||
k = j // Record the index of the smallest element
|
||||
}
|
||||
}
|
||||
// Swap the smallest element with the first element of the unsorted interval
|
||||
nums.swapAt(i, k)
|
||||
}
|
||||
}
|
||||
|
||||
@main
|
||||
enum SelectionSort {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
var nums = [4, 1, 3, 1, 5, 2]
|
||||
selectionSort(nums: &nums)
|
||||
print("After selection sort, nums = \(nums)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* File: array_deque.swift
|
||||
* Created Time: 2023-02-22
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Double-ended queue based on circular array implementation */
|
||||
class ArrayDeque {
|
||||
private var nums: [Int] // Array for storing double-ended queue elements
|
||||
private var front: Int // Front pointer, points to the front of the queue element
|
||||
private var _size: Int // Double-ended queue length
|
||||
|
||||
/* Constructor */
|
||||
init(capacity: Int) {
|
||||
nums = Array(repeating: 0, count: capacity)
|
||||
front = 0
|
||||
_size = 0
|
||||
}
|
||||
|
||||
/* Get the capacity of the double-ended queue */
|
||||
func capacity() -> Int {
|
||||
nums.count
|
||||
}
|
||||
|
||||
/* Get the length of the double-ended queue */
|
||||
func size() -> Int {
|
||||
_size
|
||||
}
|
||||
|
||||
/* Check if the double-ended queue is empty */
|
||||
func isEmpty() -> Bool {
|
||||
size() == 0
|
||||
}
|
||||
|
||||
/* Calculate circular array index */
|
||||
private func index(i: Int) -> Int {
|
||||
// Use modulo operation to wrap the array head and tail together
|
||||
// When i passes the tail of the array, return to the head
|
||||
// When i passes the head of the array, return to the tail
|
||||
(i + capacity()) % capacity()
|
||||
}
|
||||
|
||||
/* Front of the queue enqueue */
|
||||
func pushFirst(num: Int) {
|
||||
if size() == capacity() {
|
||||
print("Double-ended queue is full")
|
||||
return
|
||||
}
|
||||
// Use modulo operation to wrap front around to the tail after passing the head of the array
|
||||
// Add num to the front of the queue
|
||||
front = index(i: front - 1)
|
||||
// Add num to front of queue
|
||||
nums[front] = num
|
||||
_size += 1
|
||||
}
|
||||
|
||||
/* Rear of the queue enqueue */
|
||||
func pushLast(num: Int) {
|
||||
if size() == capacity() {
|
||||
print("Double-ended queue is full")
|
||||
return
|
||||
}
|
||||
// Use modulo operation to wrap rear around to the head after passing the tail of the array
|
||||
let rear = index(i: front + size())
|
||||
// Front pointer moves one position backward
|
||||
nums[rear] = num
|
||||
_size += 1
|
||||
}
|
||||
|
||||
/* Rear of the queue dequeue */
|
||||
func popFirst() -> Int {
|
||||
let num = peekFirst()
|
||||
// Move front pointer backward by one position
|
||||
front = index(i: front + 1)
|
||||
_size -= 1
|
||||
return num
|
||||
}
|
||||
|
||||
/* Access rear of the queue element */
|
||||
func popLast() -> Int {
|
||||
let num = peekLast()
|
||||
_size -= 1
|
||||
return num
|
||||
}
|
||||
|
||||
/* Return list for printing */
|
||||
func peekFirst() -> Int {
|
||||
if isEmpty() {
|
||||
fatalError("Deque is empty")
|
||||
}
|
||||
return nums[front]
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
func peekLast() -> Int {
|
||||
if isEmpty() {
|
||||
fatalError("Deque is empty")
|
||||
}
|
||||
// Initialize double-ended queue
|
||||
let last = index(i: front + size() - 1)
|
||||
return nums[last]
|
||||
}
|
||||
|
||||
/* Return array for printing */
|
||||
func toArray() -> [Int] {
|
||||
// Elements enqueue
|
||||
(front ..< front + size()).map { nums[index(i: $0)] }
|
||||
}
|
||||
}
|
||||
|
||||
@main
|
||||
enum _ArrayDeque {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
/* Get the length of the double-ended queue */
|
||||
let deque = ArrayDeque(capacity: 10)
|
||||
deque.pushLast(num: 3)
|
||||
deque.pushLast(num: 2)
|
||||
deque.pushLast(num: 5)
|
||||
print("Deque deque = \(deque.toArray())")
|
||||
|
||||
/* Update element */
|
||||
let peekFirst = deque.peekFirst()
|
||||
print("Front element peekFirst = \(peekFirst)")
|
||||
let peekLast = deque.peekLast()
|
||||
print("Rear element peekLast = \(peekLast)")
|
||||
|
||||
/* Elements enqueue */
|
||||
deque.pushLast(num: 4)
|
||||
print("After element 4 enqueues at rear, deque = \(deque.toArray())")
|
||||
deque.pushFirst(num: 1)
|
||||
print("After element 1 enqueues at front, deque = \(deque.toArray())")
|
||||
|
||||
/* Element dequeue */
|
||||
let popLast = deque.popLast()
|
||||
print("Dequeue rear element = \(popLast), after rear dequeue deque = \(deque.toArray())")
|
||||
let popFirst = deque.popFirst()
|
||||
print("Dequeue front element = \(popFirst), after front dequeue deque = \(deque.toArray())")
|
||||
|
||||
/* Get the length of the double-ended queue */
|
||||
let size = deque.size()
|
||||
print("Deque length size = \(size)")
|
||||
|
||||
/* Check if the double-ended queue is empty */
|
||||
let isEmpty = deque.isEmpty()
|
||||
print("Is deque empty = \(isEmpty)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* File: array_queue.swift
|
||||
* Created Time: 2023-01-11
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Queue based on circular array implementation */
|
||||
class ArrayQueue {
|
||||
private var nums: [Int] // Array for storing queue elements
|
||||
private var front: Int // Front pointer, points to the front of the queue element
|
||||
private var _size: Int // Queue length
|
||||
|
||||
init(capacity: Int) {
|
||||
// Initialize array
|
||||
nums = Array(repeating: 0, count: capacity)
|
||||
front = 0
|
||||
_size = 0
|
||||
}
|
||||
|
||||
/* Get the capacity of the queue */
|
||||
func capacity() -> Int {
|
||||
nums.count
|
||||
}
|
||||
|
||||
/* Get the length of the queue */
|
||||
func size() -> Int {
|
||||
_size
|
||||
}
|
||||
|
||||
/* Check if the queue is empty */
|
||||
func isEmpty() -> Bool {
|
||||
size() == 0
|
||||
}
|
||||
|
||||
/* Enqueue */
|
||||
func push(num: Int) {
|
||||
if size() == capacity() {
|
||||
print("Queue is full")
|
||||
return
|
||||
}
|
||||
// Use modulo operation to wrap rear around to the head after passing the tail of the array
|
||||
// Add num to the rear of the queue
|
||||
let rear = (front + size()) % capacity()
|
||||
// Front pointer moves one position backward
|
||||
nums[rear] = num
|
||||
_size += 1
|
||||
}
|
||||
|
||||
/* Dequeue */
|
||||
@discardableResult
|
||||
func pop() -> Int {
|
||||
let num = peek()
|
||||
// Move front pointer backward by one position, if it passes the tail, return to array head
|
||||
front = (front + 1) % capacity()
|
||||
_size -= 1
|
||||
return num
|
||||
}
|
||||
|
||||
/* Return list for printing */
|
||||
func peek() -> Int {
|
||||
if isEmpty() {
|
||||
fatalError("Queue is empty")
|
||||
}
|
||||
return nums[front]
|
||||
}
|
||||
|
||||
/* Return array */
|
||||
func toArray() -> [Int] {
|
||||
// Elements enqueue
|
||||
(front ..< front + size()).map { nums[$0 % capacity()] }
|
||||
}
|
||||
}
|
||||
|
||||
@main
|
||||
enum _ArrayQueue {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
/* Access front of the queue element */
|
||||
let capacity = 10
|
||||
let queue = ArrayQueue(capacity: capacity)
|
||||
|
||||
/* Elements enqueue */
|
||||
queue.push(num: 1)
|
||||
queue.push(num: 3)
|
||||
queue.push(num: 2)
|
||||
queue.push(num: 5)
|
||||
queue.push(num: 4)
|
||||
print("Queue queue = \(queue.toArray())")
|
||||
|
||||
/* Return list for printing */
|
||||
let peek = queue.peek()
|
||||
print("Front element peek = \(peek)")
|
||||
|
||||
/* Element dequeue */
|
||||
let pop = queue.pop()
|
||||
print("Dequeue element pop = \(pop), after dequeue queue = \(queue.toArray())")
|
||||
|
||||
/* Get the length of the queue */
|
||||
let size = queue.size()
|
||||
print("Queue length size = \(size)")
|
||||
|
||||
/* Check if the queue is empty */
|
||||
let isEmpty = queue.isEmpty()
|
||||
print("Is queue empty = \(isEmpty)")
|
||||
|
||||
/* Test circular array */
|
||||
for i in 0 ..< 10 {
|
||||
queue.push(num: i)
|
||||
queue.pop()
|
||||
print("After round \(i) enqueue + dequeue, queue = \(queue.toArray())")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* File: array_stack.swift
|
||||
* Created Time: 2023-01-09
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Stack based on array implementation */
|
||||
class ArrayStack {
|
||||
private var stack: [Int]
|
||||
|
||||
init() {
|
||||
// Initialize list (dynamic array)
|
||||
stack = []
|
||||
}
|
||||
|
||||
/* Get the length of the stack */
|
||||
func size() -> Int {
|
||||
stack.count
|
||||
}
|
||||
|
||||
/* Check if the stack is empty */
|
||||
func isEmpty() -> Bool {
|
||||
stack.isEmpty
|
||||
}
|
||||
|
||||
/* Push */
|
||||
func push(num: Int) {
|
||||
stack.append(num)
|
||||
}
|
||||
|
||||
/* Pop */
|
||||
@discardableResult
|
||||
func pop() -> Int {
|
||||
if isEmpty() {
|
||||
fatalError("Stack is empty")
|
||||
}
|
||||
return stack.removeLast()
|
||||
}
|
||||
|
||||
/* Return list for printing */
|
||||
func peek() -> Int {
|
||||
if isEmpty() {
|
||||
fatalError("Stack is empty")
|
||||
}
|
||||
return stack.last!
|
||||
}
|
||||
|
||||
/* Convert List to Array and return */
|
||||
func toArray() -> [Int] {
|
||||
stack
|
||||
}
|
||||
}
|
||||
|
||||
@main
|
||||
enum _ArrayStack {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
/* Access top of the stack element */
|
||||
let stack = ArrayStack()
|
||||
|
||||
/* Elements push onto stack */
|
||||
stack.push(num: 1)
|
||||
stack.push(num: 3)
|
||||
stack.push(num: 2)
|
||||
stack.push(num: 5)
|
||||
stack.push(num: 4)
|
||||
print("Stack stack = \(stack.toArray())")
|
||||
|
||||
/* Return list for printing */
|
||||
let peek = stack.peek()
|
||||
print("Top element peek = \(peek)")
|
||||
|
||||
/* Element pop from stack */
|
||||
let pop = stack.pop()
|
||||
print("Pop element pop = \(pop), after pop stack = \(stack.toArray())")
|
||||
|
||||
/* Get the length of the stack */
|
||||
let size = stack.size()
|
||||
print("Stack length size = \(size)")
|
||||
|
||||
/* Check if empty */
|
||||
let isEmpty = stack.isEmpty()
|
||||
print("Is stack empty = \(isEmpty)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* File: deque.swift
|
||||
* Created Time: 2023-01-14
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
@main
|
||||
enum Deque {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
/* Get the length of the double-ended queue */
|
||||
// Swift has no built-in deque class, can use Array as deque
|
||||
var deque: [Int] = []
|
||||
|
||||
/* Elements enqueue */
|
||||
deque.append(2)
|
||||
deque.append(5)
|
||||
deque.append(4)
|
||||
deque.insert(3, at: 0)
|
||||
deque.insert(1, at: 0)
|
||||
print("Deque deque = \(deque)")
|
||||
|
||||
/* Update element */
|
||||
let peekFirst = deque.first!
|
||||
print("Front element peekFirst = \(peekFirst)")
|
||||
let peekLast = deque.last!
|
||||
print("Rear element peekLast = \(peekLast)")
|
||||
|
||||
/* Element dequeue */
|
||||
// When simulating with Array, popFirst complexity is O(n)
|
||||
let popFirst = deque.removeFirst()
|
||||
print("Dequeue front element popFirst = \(popFirst), after front dequeue deque = \(deque)")
|
||||
let popLast = deque.removeLast()
|
||||
print("Dequeue rear element popLast = \(popLast), after rear dequeue deque = \(deque)")
|
||||
|
||||
/* Get the length of the double-ended queue */
|
||||
let size = deque.count
|
||||
print("Deque length size = \(size)")
|
||||
|
||||
/* Check if the double-ended queue is empty */
|
||||
let isEmpty = deque.isEmpty
|
||||
print("Is deque empty = \(isEmpty)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
/**
|
||||
* File: linkedlist_deque.swift
|
||||
* Created Time: 2023-02-22
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Doubly linked list node */
|
||||
class ListNode {
|
||||
var val: Int // Node value
|
||||
var next: ListNode? // Successor node reference
|
||||
weak var prev: ListNode? // Predecessor node reference
|
||||
|
||||
init(val: Int) {
|
||||
self.val = val
|
||||
}
|
||||
}
|
||||
|
||||
/* Double-ended queue based on doubly linked list implementation */
|
||||
class LinkedListDeque {
|
||||
private var front: ListNode? // Head node front
|
||||
private var rear: ListNode? // Tail node rear
|
||||
private var _size: Int // Length of the double-ended queue
|
||||
|
||||
init() {
|
||||
_size = 0
|
||||
}
|
||||
|
||||
/* Get the length of the double-ended queue */
|
||||
func size() -> Int {
|
||||
_size
|
||||
}
|
||||
|
||||
/* Check if the double-ended queue is empty */
|
||||
func isEmpty() -> Bool {
|
||||
size() == 0
|
||||
}
|
||||
|
||||
/* Enqueue operation */
|
||||
private func push(num: Int, isFront: Bool) {
|
||||
let node = ListNode(val: num)
|
||||
// If the linked list is empty, make both front and rear point to node
|
||||
if isEmpty() {
|
||||
front = node
|
||||
rear = node
|
||||
}
|
||||
// Front of the queue enqueue operation
|
||||
else if isFront {
|
||||
// Add node to the head of the linked list
|
||||
front?.prev = node
|
||||
node.next = front
|
||||
front = node // Update head node
|
||||
}
|
||||
// Rear of the queue enqueue operation
|
||||
else {
|
||||
// Add node to the tail of the linked list
|
||||
rear?.next = node
|
||||
node.prev = rear
|
||||
rear = node // Update tail node
|
||||
}
|
||||
_size += 1 // Update queue length
|
||||
}
|
||||
|
||||
/* Front of the queue enqueue */
|
||||
func pushFirst(num: Int) {
|
||||
push(num: num, isFront: true)
|
||||
}
|
||||
|
||||
/* Rear of the queue enqueue */
|
||||
func pushLast(num: Int) {
|
||||
push(num: num, isFront: false)
|
||||
}
|
||||
|
||||
/* Dequeue operation */
|
||||
private func pop(isFront: Bool) -> Int {
|
||||
if isEmpty() {
|
||||
fatalError("Deque is empty")
|
||||
}
|
||||
let val: Int
|
||||
// Temporarily store head node value
|
||||
if isFront {
|
||||
val = front!.val // Delete head node
|
||||
// Delete head node
|
||||
let fNext = front?.next
|
||||
if fNext != nil {
|
||||
fNext?.prev = nil
|
||||
front?.next = nil
|
||||
}
|
||||
front = fNext // Update head node
|
||||
}
|
||||
// Temporarily store tail node value
|
||||
else {
|
||||
val = rear!.val // Delete tail node
|
||||
// Update tail node
|
||||
let rPrev = rear?.prev
|
||||
if rPrev != nil {
|
||||
rPrev?.next = nil
|
||||
rear?.prev = nil
|
||||
}
|
||||
rear = rPrev // Update tail node
|
||||
}
|
||||
_size -= 1 // Update queue length
|
||||
return val
|
||||
}
|
||||
|
||||
/* Rear of the queue dequeue */
|
||||
func popFirst() -> Int {
|
||||
pop(isFront: true)
|
||||
}
|
||||
|
||||
/* Access rear of the queue element */
|
||||
func popLast() -> Int {
|
||||
pop(isFront: false)
|
||||
}
|
||||
|
||||
/* Return list for printing */
|
||||
func peekFirst() -> Int {
|
||||
if isEmpty() {
|
||||
fatalError("Deque is empty")
|
||||
}
|
||||
return front!.val
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
func peekLast() -> Int {
|
||||
if isEmpty() {
|
||||
fatalError("Deque is empty")
|
||||
}
|
||||
return rear!.val
|
||||
}
|
||||
|
||||
/* Return array for printing */
|
||||
func toArray() -> [Int] {
|
||||
var node = front
|
||||
var res = Array(repeating: 0, count: size())
|
||||
for i in res.indices {
|
||||
res[i] = node!.val
|
||||
node = node?.next
|
||||
}
|
||||
return res
|
||||
}
|
||||
}
|
||||
|
||||
@main
|
||||
enum _LinkedListDeque {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
/* Get the length of the double-ended queue */
|
||||
let deque = LinkedListDeque()
|
||||
deque.pushLast(num: 3)
|
||||
deque.pushLast(num: 2)
|
||||
deque.pushLast(num: 5)
|
||||
print("Deque deque = \(deque.toArray())")
|
||||
|
||||
/* Update element */
|
||||
let peekFirst = deque.peekFirst()
|
||||
print("Front element peekFirst = \(peekFirst)")
|
||||
let peekLast = deque.peekLast()
|
||||
print("Rear element peekLast = \(peekLast)")
|
||||
|
||||
/* Elements enqueue */
|
||||
deque.pushLast(num: 4)
|
||||
print("After element 4 enqueues at rear, deque = \(deque.toArray())")
|
||||
deque.pushFirst(num: 1)
|
||||
print("After element 1 enqueues at front, deque = \(deque.toArray())")
|
||||
|
||||
/* Element dequeue */
|
||||
let popLast = deque.popLast()
|
||||
print("Dequeue rear element = \(popLast), after rear dequeue deque = \(deque.toArray())")
|
||||
let popFirst = deque.popFirst()
|
||||
print("Dequeue front element = \(popFirst), after front dequeue deque = \(deque.toArray())")
|
||||
|
||||
/* Get the length of the double-ended queue */
|
||||
let size = deque.size()
|
||||
print("Deque length size = \(size)")
|
||||
|
||||
/* Check if the double-ended queue is empty */
|
||||
let isEmpty = deque.isEmpty()
|
||||
print("Is deque empty = \(isEmpty)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* File: linkedlist_queue.swift
|
||||
* Created Time: 2023-01-11
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
import utils
|
||||
|
||||
/* Queue based on linked list implementation */
|
||||
class LinkedListQueue {
|
||||
private var front: ListNode? // Head node
|
||||
private var rear: ListNode? // Tail node
|
||||
private var _size: Int
|
||||
|
||||
init() {
|
||||
_size = 0
|
||||
}
|
||||
|
||||
/* Get the length of the queue */
|
||||
func size() -> Int {
|
||||
_size
|
||||
}
|
||||
|
||||
/* Check if the queue is empty */
|
||||
func isEmpty() -> Bool {
|
||||
size() == 0
|
||||
}
|
||||
|
||||
/* Enqueue */
|
||||
func push(num: Int) {
|
||||
// Add num after the tail node
|
||||
let node = ListNode(x: num)
|
||||
// If the queue is empty, make both front and rear point to the node
|
||||
if front == nil {
|
||||
front = node
|
||||
rear = node
|
||||
}
|
||||
// If the queue is not empty, add the node after the tail node
|
||||
else {
|
||||
rear?.next = node
|
||||
rear = node
|
||||
}
|
||||
_size += 1
|
||||
}
|
||||
|
||||
/* Dequeue */
|
||||
@discardableResult
|
||||
func pop() -> Int {
|
||||
let num = peek()
|
||||
// Delete head node
|
||||
front = front?.next
|
||||
_size -= 1
|
||||
return num
|
||||
}
|
||||
|
||||
/* Return list for printing */
|
||||
func peek() -> Int {
|
||||
if isEmpty() {
|
||||
fatalError("Queue is empty")
|
||||
}
|
||||
return front!.val
|
||||
}
|
||||
|
||||
/* Convert linked list to Array and return */
|
||||
func toArray() -> [Int] {
|
||||
var node = front
|
||||
var res = Array(repeating: 0, count: size())
|
||||
for i in res.indices {
|
||||
res[i] = node!.val
|
||||
node = node?.next
|
||||
}
|
||||
return res
|
||||
}
|
||||
}
|
||||
|
||||
@main
|
||||
enum _LinkedListQueue {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
/* Access front of the queue element */
|
||||
let queue = LinkedListQueue()
|
||||
|
||||
/* Elements enqueue */
|
||||
queue.push(num: 1)
|
||||
queue.push(num: 3)
|
||||
queue.push(num: 2)
|
||||
queue.push(num: 5)
|
||||
queue.push(num: 4)
|
||||
print("Queue queue = \(queue.toArray())")
|
||||
|
||||
/* Return list for printing */
|
||||
let peek = queue.peek()
|
||||
print("Front element peek = \(peek)")
|
||||
|
||||
/* Element dequeue */
|
||||
let pop = queue.pop()
|
||||
print("Dequeue element pop = \(pop), after dequeue queue = \(queue.toArray())")
|
||||
|
||||
/* Get the length of the queue */
|
||||
let size = queue.size()
|
||||
print("Queue length size = \(size)")
|
||||
|
||||
/* Check if the queue is empty */
|
||||
let isEmpty = queue.isEmpty()
|
||||
print("Is queue empty = \(isEmpty)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* File: linkedlist_stack.swift
|
||||
* Created Time: 2023-01-09
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
import utils
|
||||
|
||||
/* Stack based on linked list implementation */
|
||||
class LinkedListStack {
|
||||
private var _peek: ListNode? // Use head node as stack top
|
||||
private var _size: Int // Stack length
|
||||
|
||||
init() {
|
||||
_size = 0
|
||||
}
|
||||
|
||||
/* Get the length of the stack */
|
||||
func size() -> Int {
|
||||
_size
|
||||
}
|
||||
|
||||
/* Check if the stack is empty */
|
||||
func isEmpty() -> Bool {
|
||||
size() == 0
|
||||
}
|
||||
|
||||
/* Push */
|
||||
func push(num: Int) {
|
||||
let node = ListNode(x: num)
|
||||
node.next = _peek
|
||||
_peek = node
|
||||
_size += 1
|
||||
}
|
||||
|
||||
/* Pop */
|
||||
@discardableResult
|
||||
func pop() -> Int {
|
||||
let num = peek()
|
||||
_peek = _peek?.next
|
||||
_size -= 1
|
||||
return num
|
||||
}
|
||||
|
||||
/* Return list for printing */
|
||||
func peek() -> Int {
|
||||
if isEmpty() {
|
||||
fatalError("Stack is empty")
|
||||
}
|
||||
return _peek!.val
|
||||
}
|
||||
|
||||
/* Convert List to Array and return */
|
||||
func toArray() -> [Int] {
|
||||
var node = _peek
|
||||
var res = Array(repeating: 0, count: size())
|
||||
for i in res.indices.reversed() {
|
||||
res[i] = node!.val
|
||||
node = node?.next
|
||||
}
|
||||
return res
|
||||
}
|
||||
}
|
||||
|
||||
@main
|
||||
enum _LinkedListStack {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
/* Access top of the stack element */
|
||||
let stack = LinkedListStack()
|
||||
|
||||
/* Elements push onto stack */
|
||||
stack.push(num: 1)
|
||||
stack.push(num: 3)
|
||||
stack.push(num: 2)
|
||||
stack.push(num: 5)
|
||||
stack.push(num: 4)
|
||||
print("Stack stack = \(stack.toArray())")
|
||||
|
||||
/* Return list for printing */
|
||||
let peek = stack.peek()
|
||||
print("Top element peek = \(peek)")
|
||||
|
||||
/* Element pop from stack */
|
||||
let pop = stack.pop()
|
||||
print("Pop element pop = \(pop), after pop stack = \(stack.toArray())")
|
||||
|
||||
/* Get the length of the stack */
|
||||
let size = stack.size()
|
||||
print("Stack length size = \(size)")
|
||||
|
||||
/* Check if empty */
|
||||
let isEmpty = stack.isEmpty()
|
||||
print("Is stack empty = \(isEmpty)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* File: queue.swift
|
||||
* Created Time: 2023-01-11
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
@main
|
||||
enum Queue {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
/* Access front of the queue element */
|
||||
// Swift has no built-in queue class, can use Array as queue
|
||||
var queue: [Int] = []
|
||||
|
||||
/* Elements enqueue */
|
||||
queue.append(1)
|
||||
queue.append(3)
|
||||
queue.append(2)
|
||||
queue.append(5)
|
||||
queue.append(4)
|
||||
print("Queue queue = \(queue)")
|
||||
|
||||
/* Return list for printing */
|
||||
let peek = queue.first!
|
||||
print("Front element peek = \(peek)")
|
||||
|
||||
/* Element dequeue */
|
||||
// When simulating with Array, pop complexity is O(n)
|
||||
let pool = queue.removeFirst()
|
||||
print("Dequeue element pop = \(pool), after dequeue queue = \(queue)")
|
||||
|
||||
/* Get the length of the queue */
|
||||
let size = queue.count
|
||||
print("Queue length size = \(size)")
|
||||
|
||||
/* Check if the queue is empty */
|
||||
let isEmpty = queue.isEmpty
|
||||
print("Is queue empty = \(isEmpty)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* File: stack.swift
|
||||
* Created Time: 2023-01-09
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
@main
|
||||
enum Stack {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
/* Access top of the stack element */
|
||||
// Swift has no built-in stack class, can use Array as stack
|
||||
var stack: [Int] = []
|
||||
|
||||
/* Elements push onto stack */
|
||||
stack.append(1)
|
||||
stack.append(3)
|
||||
stack.append(2)
|
||||
stack.append(5)
|
||||
stack.append(4)
|
||||
print("Stack stack = \(stack)")
|
||||
|
||||
/* Return list for printing */
|
||||
let peek = stack.last!
|
||||
print("Top element peek = \(peek)")
|
||||
|
||||
/* Element pop from stack */
|
||||
let pop = stack.removeLast()
|
||||
print("Pop element pop = \(pop), after pop stack = \(stack)")
|
||||
|
||||
/* Get the length of the stack */
|
||||
let size = stack.count
|
||||
print("Stack length size = \(size)")
|
||||
|
||||
/* Check if empty */
|
||||
let isEmpty = stack.isEmpty
|
||||
print("Is stack empty = \(isEmpty)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
/**
|
||||
* File: array_binary_tree.swift
|
||||
* Created Time: 2023-07-23
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
import utils
|
||||
|
||||
/* Binary tree class represented by array */
|
||||
class ArrayBinaryTree {
|
||||
private var tree: [Int?]
|
||||
|
||||
/* Constructor */
|
||||
init(arr: [Int?]) {
|
||||
tree = arr
|
||||
}
|
||||
|
||||
/* List capacity */
|
||||
func size() -> Int {
|
||||
tree.count
|
||||
}
|
||||
|
||||
/* Get value of node at index i */
|
||||
func val(i: Int) -> Int? {
|
||||
// If index out of bounds, return null to represent empty position
|
||||
if i < 0 || i >= size() {
|
||||
return nil
|
||||
}
|
||||
return tree[i]
|
||||
}
|
||||
|
||||
/* Get index of left child node of node at index i */
|
||||
func left(i: Int) -> Int {
|
||||
2 * i + 1
|
||||
}
|
||||
|
||||
/* Get index of right child node of node at index i */
|
||||
func right(i: Int) -> Int {
|
||||
2 * i + 2
|
||||
}
|
||||
|
||||
/* Get index of parent node of node at index i */
|
||||
func parent(i: Int) -> Int {
|
||||
(i - 1) / 2
|
||||
}
|
||||
|
||||
/* Level-order traversal */
|
||||
func levelOrder() -> [Int] {
|
||||
var res: [Int] = []
|
||||
// Traverse array directly
|
||||
for i in 0 ..< size() {
|
||||
if let val = val(i: i) {
|
||||
res.append(val)
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
/* Depth-first traversal */
|
||||
private func dfs(i: Int, order: String, res: inout [Int]) {
|
||||
// If empty position, return
|
||||
guard let val = val(i: i) else {
|
||||
return
|
||||
}
|
||||
// Preorder traversal
|
||||
if order == "pre" {
|
||||
res.append(val)
|
||||
}
|
||||
dfs(i: left(i: i), order: order, res: &res)
|
||||
// Inorder traversal
|
||||
if order == "in" {
|
||||
res.append(val)
|
||||
}
|
||||
dfs(i: right(i: i), order: order, res: &res)
|
||||
// Postorder traversal
|
||||
if order == "post" {
|
||||
res.append(val)
|
||||
}
|
||||
}
|
||||
|
||||
/* Preorder traversal */
|
||||
func preOrder() -> [Int] {
|
||||
var res: [Int] = []
|
||||
dfs(i: 0, order: "pre", res: &res)
|
||||
return res
|
||||
}
|
||||
|
||||
/* Inorder traversal */
|
||||
func inOrder() -> [Int] {
|
||||
var res: [Int] = []
|
||||
dfs(i: 0, order: "in", res: &res)
|
||||
return res
|
||||
}
|
||||
|
||||
/* Postorder traversal */
|
||||
func postOrder() -> [Int] {
|
||||
var res: [Int] = []
|
||||
dfs(i: 0, order: "post", res: &res)
|
||||
return res
|
||||
}
|
||||
}
|
||||
|
||||
@main
|
||||
enum _ArrayBinaryTree {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
// Initialize binary tree
|
||||
// Here we use a function to generate a binary tree directly from an array
|
||||
let arr = [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15]
|
||||
|
||||
let root = TreeNode.listToTree(arr: arr)
|
||||
print("\nInitialize binary tree\n")
|
||||
print("Array representation of binary tree:")
|
||||
print(arr)
|
||||
print("Linked list representation of binary tree:")
|
||||
PrintUtil.printTree(root: root)
|
||||
|
||||
// Binary tree class represented by array
|
||||
let abt = ArrayBinaryTree(arr: arr)
|
||||
|
||||
// Access node
|
||||
let i = 1
|
||||
let l = abt.left(i: i)
|
||||
let r = abt.right(i: i)
|
||||
let p = abt.parent(i: i)
|
||||
print("\nCurrent node index is \(i), value is \(abt.val(i: i) as Any)")
|
||||
print("Its left child index is \(l), value is \(abt.val(i: l) as Any)")
|
||||
print("Its right child index is \(r), value is \(abt.val(i: r) as Any)")
|
||||
print("Its parent node index is \(p), value is \(abt.val(i: p) as Any)")
|
||||
|
||||
// Traverse tree
|
||||
var res = abt.levelOrder()
|
||||
print("\nLevel-order traversal is: \(res)")
|
||||
res = abt.preOrder()
|
||||
print("Pre-order traversal is: \(res)")
|
||||
res = abt.inOrder()
|
||||
print("In-order traversal is: \(res)")
|
||||
res = abt.postOrder()
|
||||
print("Post-order traversal is: \(res)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
/**
|
||||
* File: avl_tree.swift
|
||||
* Created Time: 2023-01-28
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
import utils
|
||||
|
||||
/* AVL tree */
|
||||
class AVLTree {
|
||||
fileprivate var root: TreeNode? // Root node
|
||||
|
||||
init() {}
|
||||
|
||||
/* Get node height */
|
||||
func height(node: TreeNode?) -> Int {
|
||||
// Empty node height is -1, leaf node height is 0
|
||||
node?.height ?? -1
|
||||
}
|
||||
|
||||
/* Update node height */
|
||||
private func updateHeight(node: TreeNode?) {
|
||||
// Node height equals the height of the tallest subtree + 1
|
||||
node?.height = max(height(node: node?.left), height(node: node?.right)) + 1
|
||||
}
|
||||
|
||||
/* Get balance factor */
|
||||
func balanceFactor(node: TreeNode?) -> Int {
|
||||
// Empty node balance factor is 0
|
||||
guard let node = node else { return 0 }
|
||||
// Node balance factor = left subtree height - right subtree height
|
||||
return height(node: node.left) - height(node: node.right)
|
||||
}
|
||||
|
||||
/* Right rotation operation */
|
||||
private func rightRotate(node: TreeNode?) -> TreeNode? {
|
||||
let child = node?.left
|
||||
let grandChild = child?.right
|
||||
// Using child as pivot, rotate node to the right
|
||||
child?.right = node
|
||||
node?.left = grandChild
|
||||
// Update node height
|
||||
updateHeight(node: node)
|
||||
updateHeight(node: child)
|
||||
// Return root node of subtree after rotation
|
||||
return child
|
||||
}
|
||||
|
||||
/* Left rotation operation */
|
||||
private func leftRotate(node: TreeNode?) -> TreeNode? {
|
||||
let child = node?.right
|
||||
let grandChild = child?.left
|
||||
// Using child as pivot, rotate node to the left
|
||||
child?.left = node
|
||||
node?.right = grandChild
|
||||
// Update node height
|
||||
updateHeight(node: node)
|
||||
updateHeight(node: child)
|
||||
// Return root node of subtree after rotation
|
||||
return child
|
||||
}
|
||||
|
||||
/* Perform rotation operation to restore balance to this subtree */
|
||||
private func rotate(node: TreeNode?) -> TreeNode? {
|
||||
// Get balance factor of node
|
||||
let balanceFactor = balanceFactor(node: node)
|
||||
// Left-leaning tree
|
||||
if balanceFactor > 1 {
|
||||
if self.balanceFactor(node: node?.left) >= 0 {
|
||||
// Right rotation
|
||||
return rightRotate(node: node)
|
||||
} else {
|
||||
// First left rotation then right rotation
|
||||
node?.left = leftRotate(node: node?.left)
|
||||
return rightRotate(node: node)
|
||||
}
|
||||
}
|
||||
// Right-leaning tree
|
||||
if balanceFactor < -1 {
|
||||
if self.balanceFactor(node: node?.right) <= 0 {
|
||||
// Left rotation
|
||||
return leftRotate(node: node)
|
||||
} else {
|
||||
// First right rotation then left rotation
|
||||
node?.right = rightRotate(node: node?.right)
|
||||
return leftRotate(node: node)
|
||||
}
|
||||
}
|
||||
// Balanced tree, no rotation needed, return directly
|
||||
return node
|
||||
}
|
||||
|
||||
/* Insert node */
|
||||
func insert(val: Int) {
|
||||
root = insertHelper(node: root, val: val)
|
||||
}
|
||||
|
||||
/* Recursively insert node (helper method) */
|
||||
private func insertHelper(node: TreeNode?, val: Int) -> TreeNode? {
|
||||
var node = node
|
||||
if node == nil {
|
||||
return TreeNode(x: val)
|
||||
}
|
||||
/* 1. Find insertion position and insert node */
|
||||
if val < node!.val {
|
||||
node?.left = insertHelper(node: node?.left, val: val)
|
||||
} else if val > node!.val {
|
||||
node?.right = insertHelper(node: node?.right, val: val)
|
||||
} else {
|
||||
return node // Duplicate node not inserted, return directly
|
||||
}
|
||||
updateHeight(node: node) // Update node height
|
||||
/* 2. Perform rotation operation to restore balance to this subtree */
|
||||
node = rotate(node: node)
|
||||
// Return root node of subtree
|
||||
return node
|
||||
}
|
||||
|
||||
/* Remove node */
|
||||
func remove(val: Int) {
|
||||
root = removeHelper(node: root, val: val)
|
||||
}
|
||||
|
||||
/* Recursively delete node (helper method) */
|
||||
private func removeHelper(node: TreeNode?, val: Int) -> TreeNode? {
|
||||
var node = node
|
||||
if node == nil {
|
||||
return nil
|
||||
}
|
||||
/* 1. Find node and delete */
|
||||
if val < node!.val {
|
||||
node?.left = removeHelper(node: node?.left, val: val)
|
||||
} else if val > node!.val {
|
||||
node?.right = removeHelper(node: node?.right, val: val)
|
||||
} else {
|
||||
if node?.left == nil || node?.right == nil {
|
||||
let child = node?.left ?? node?.right
|
||||
// Number of child nodes = 0, delete node directly and return
|
||||
if child == nil {
|
||||
return nil
|
||||
}
|
||||
// Number of child nodes = 1, delete node directly
|
||||
else {
|
||||
node = child
|
||||
}
|
||||
} else {
|
||||
// Number of child nodes = 2, delete the next node in inorder traversal and replace current node with it
|
||||
var temp = node?.right
|
||||
while temp?.left != nil {
|
||||
temp = temp?.left
|
||||
}
|
||||
node?.right = removeHelper(node: node?.right, val: temp!.val)
|
||||
node?.val = temp!.val
|
||||
}
|
||||
}
|
||||
updateHeight(node: node) // Update node height
|
||||
/* 2. Perform rotation operation to restore balance to this subtree */
|
||||
node = rotate(node: node)
|
||||
// Return root node of subtree
|
||||
return node
|
||||
}
|
||||
|
||||
/* Search node */
|
||||
func search(val: Int) -> TreeNode? {
|
||||
var cur = root
|
||||
while cur != nil {
|
||||
// Target node is in cur's right subtree
|
||||
if cur!.val < val {
|
||||
cur = cur?.right
|
||||
}
|
||||
// Target node is in cur's left subtree
|
||||
else if cur!.val > val {
|
||||
cur = cur?.left
|
||||
}
|
||||
// Found target node, exit loop
|
||||
else {
|
||||
break
|
||||
}
|
||||
}
|
||||
// Return target node
|
||||
return cur
|
||||
}
|
||||
}
|
||||
|
||||
@main
|
||||
enum _AVLTree {
|
||||
static func testInsert(tree: AVLTree, val: Int) {
|
||||
tree.insert(val: val)
|
||||
print("\nAfter inserting node \(val), AVL tree is")
|
||||
PrintUtil.printTree(root: tree.root)
|
||||
}
|
||||
|
||||
static func testRemove(tree: AVLTree, val: Int) {
|
||||
tree.remove(val: val)
|
||||
print("\nAfter deleting node \(val), AVL tree is")
|
||||
PrintUtil.printTree(root: tree.root)
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
/* Please pay attention to how the AVL tree maintains balance after inserting nodes */
|
||||
let avlTree = AVLTree()
|
||||
|
||||
/* Insert node */
|
||||
// Delete nodes
|
||||
testInsert(tree: avlTree, val: 1)
|
||||
testInsert(tree: avlTree, val: 2)
|
||||
testInsert(tree: avlTree, val: 3)
|
||||
testInsert(tree: avlTree, val: 4)
|
||||
testInsert(tree: avlTree, val: 5)
|
||||
testInsert(tree: avlTree, val: 8)
|
||||
testInsert(tree: avlTree, val: 7)
|
||||
testInsert(tree: avlTree, val: 9)
|
||||
testInsert(tree: avlTree, val: 10)
|
||||
testInsert(tree: avlTree, val: 6)
|
||||
|
||||
/* Please pay attention to how the AVL tree maintains balance after deleting nodes */
|
||||
testInsert(tree: avlTree, val: 7)
|
||||
|
||||
/* Remove node */
|
||||
// Delete node with degree 1
|
||||
testRemove(tree: avlTree, val: 8) // Delete node with degree 2
|
||||
testRemove(tree: avlTree, val: 5) // Remove node with degree 1
|
||||
testRemove(tree: avlTree, val: 4) // Remove node with degree 2
|
||||
|
||||
/* Search node */
|
||||
let node = avlTree.search(val: 7)
|
||||
print("\nFound node object is \(node!), node value = \(node!.val)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
/**
|
||||
* File: binary_search_tree.swift
|
||||
* Created Time: 2023-01-26
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
import utils
|
||||
|
||||
/* Binary search tree */
|
||||
class BinarySearchTree {
|
||||
private var root: TreeNode?
|
||||
|
||||
/* Constructor */
|
||||
init() {
|
||||
// Initialize empty tree
|
||||
root = nil
|
||||
}
|
||||
|
||||
/* Get binary tree root node */
|
||||
func getRoot() -> TreeNode? {
|
||||
root
|
||||
}
|
||||
|
||||
/* Search node */
|
||||
func search(num: Int) -> TreeNode? {
|
||||
var cur = root
|
||||
// Loop search, exit after passing leaf node
|
||||
while cur != nil {
|
||||
// Target node is in cur's right subtree
|
||||
if cur!.val < num {
|
||||
cur = cur?.right
|
||||
}
|
||||
// Target node is in cur's left subtree
|
||||
else if cur!.val > num {
|
||||
cur = cur?.left
|
||||
}
|
||||
// Found target node, exit loop
|
||||
else {
|
||||
break
|
||||
}
|
||||
}
|
||||
// Return target node
|
||||
return cur
|
||||
}
|
||||
|
||||
/* Insert node */
|
||||
func insert(num: Int) {
|
||||
// If tree is empty, initialize root node
|
||||
if root == nil {
|
||||
root = TreeNode(x: num)
|
||||
return
|
||||
}
|
||||
var cur = root
|
||||
var pre: TreeNode?
|
||||
// Loop search, exit after passing leaf node
|
||||
while cur != nil {
|
||||
// Found duplicate node, return directly
|
||||
if cur!.val == num {
|
||||
return
|
||||
}
|
||||
pre = cur
|
||||
// Insertion position is in cur's right subtree
|
||||
if cur!.val < num {
|
||||
cur = cur?.right
|
||||
}
|
||||
// Insertion position is in cur's left subtree
|
||||
else {
|
||||
cur = cur?.left
|
||||
}
|
||||
}
|
||||
// Insert node
|
||||
let node = TreeNode(x: num)
|
||||
if pre!.val < num {
|
||||
pre?.right = node
|
||||
} else {
|
||||
pre?.left = node
|
||||
}
|
||||
}
|
||||
|
||||
/* Remove node */
|
||||
func remove(num: Int) {
|
||||
// If tree is empty, return directly
|
||||
if root == nil {
|
||||
return
|
||||
}
|
||||
var cur = root
|
||||
var pre: TreeNode?
|
||||
// Loop search, exit after passing leaf node
|
||||
while cur != nil {
|
||||
// Found node to delete, exit loop
|
||||
if cur!.val == num {
|
||||
break
|
||||
}
|
||||
pre = cur
|
||||
// Node to delete is in cur's right subtree
|
||||
if cur!.val < num {
|
||||
cur = cur?.right
|
||||
}
|
||||
// Node to delete is in cur's left subtree
|
||||
else {
|
||||
cur = cur?.left
|
||||
}
|
||||
}
|
||||
// If no node to delete, return directly
|
||||
if cur == nil {
|
||||
return
|
||||
}
|
||||
// Number of child nodes = 0 or 1
|
||||
if cur?.left == nil || cur?.right == nil {
|
||||
// When number of child nodes = 0 / 1, child = null / that child node
|
||||
let child = cur?.left ?? cur?.right
|
||||
// Delete node cur
|
||||
if cur !== root {
|
||||
if pre?.left === cur {
|
||||
pre?.left = child
|
||||
} else {
|
||||
pre?.right = child
|
||||
}
|
||||
} else {
|
||||
// If deleted node is root node, reassign root node
|
||||
root = child
|
||||
}
|
||||
}
|
||||
// Number of child nodes = 2
|
||||
else {
|
||||
// Get next node of cur in inorder traversal
|
||||
var tmp = cur?.right
|
||||
while tmp?.left != nil {
|
||||
tmp = tmp?.left
|
||||
}
|
||||
// Recursively delete node tmp
|
||||
remove(num: tmp!.val)
|
||||
// Replace cur with tmp
|
||||
cur?.val = tmp!.val
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@main
|
||||
enum _BinarySearchTree {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
/* Initialize binary search tree */
|
||||
let bst = BinarySearchTree()
|
||||
// Please note that different insertion orders will generate different binary trees, this sequence can generate a perfect binary tree
|
||||
let nums = [8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15]
|
||||
for num in nums {
|
||||
bst.insert(num: num)
|
||||
}
|
||||
print("\nInitialized binary tree is\n")
|
||||
PrintUtil.printTree(root: bst.getRoot())
|
||||
|
||||
/* Search node */
|
||||
let node = bst.search(num: 7)
|
||||
print("\nFound node object is \(node!), node value = \(node!.val)")
|
||||
|
||||
/* Insert node */
|
||||
bst.insert(num: 16)
|
||||
print("\nAfter inserting node 16, binary tree is\n")
|
||||
PrintUtil.printTree(root: bst.getRoot())
|
||||
|
||||
/* Remove node */
|
||||
bst.remove(num: 1)
|
||||
print("\nAfter removing node 1, binary tree is\n")
|
||||
PrintUtil.printTree(root: bst.getRoot())
|
||||
bst.remove(num: 2)
|
||||
print("\nAfter removing node 2, binary tree is\n")
|
||||
PrintUtil.printTree(root: bst.getRoot())
|
||||
bst.remove(num: 4)
|
||||
print("\nAfter removing node 4, binary tree is\n")
|
||||
PrintUtil.printTree(root: bst.getRoot())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* File: binary_tree.swift
|
||||
* Created Time: 2023-01-18
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
import utils
|
||||
|
||||
@main
|
||||
enum BinaryTree {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
/* Initialize binary tree */
|
||||
// Initialize nodes
|
||||
let n1 = TreeNode(x: 1)
|
||||
let n2 = TreeNode(x: 2)
|
||||
let n3 = TreeNode(x: 3)
|
||||
let n4 = TreeNode(x: 4)
|
||||
let n5 = TreeNode(x: 5)
|
||||
// Build references (pointers) between nodes
|
||||
n1.left = n2
|
||||
n1.right = n3
|
||||
n2.left = n4
|
||||
n2.right = n5
|
||||
print("\nInitialize binary tree\n")
|
||||
PrintUtil.printTree(root: n1)
|
||||
|
||||
/* Insert node P between n1 -> n2 */
|
||||
let P = TreeNode(x: 0)
|
||||
// Delete node
|
||||
n1.left = P
|
||||
P.left = n2
|
||||
print("\nAfter inserting node P\n")
|
||||
PrintUtil.printTree(root: n1)
|
||||
// Remove node P
|
||||
n1.left = n2
|
||||
print("\nAfter removing node P\n")
|
||||
PrintUtil.printTree(root: n1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* File: binary_tree_bfs.swift
|
||||
* Created Time: 2023-01-18
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
import utils
|
||||
|
||||
/* Level-order traversal */
|
||||
func levelOrder(root: TreeNode) -> [Int] {
|
||||
// Initialize queue, add root node
|
||||
var queue: [TreeNode] = [root]
|
||||
// Initialize a list to save the traversal sequence
|
||||
var list: [Int] = []
|
||||
while !queue.isEmpty {
|
||||
let node = queue.removeFirst() // Dequeue
|
||||
list.append(node.val) // Save node value
|
||||
if let left = node.left {
|
||||
queue.append(left) // Left child node enqueue
|
||||
}
|
||||
if let right = node.right {
|
||||
queue.append(right) // Right child node enqueue
|
||||
}
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
||||
@main
|
||||
enum BinaryTreeBFS {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
/* Initialize binary tree */
|
||||
// Here we use a function to generate a binary tree directly from an array
|
||||
let node = TreeNode.listToTree(arr: [1, 2, 3, 4, 5, 6, 7])!
|
||||
print("\nInitialize binary tree\n")
|
||||
PrintUtil.printTree(root: node)
|
||||
|
||||
/* Level-order traversal */
|
||||
let list = levelOrder(root: node)
|
||||
print("\nLevel-order traversal node print sequence = \(list)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* File: binary_tree_dfs.swift
|
||||
* Created Time: 2023-01-18
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
import utils
|
||||
|
||||
// Initialize list for storing traversal sequence
|
||||
var list: [Int] = []
|
||||
|
||||
/* Preorder traversal */
|
||||
func preOrder(root: TreeNode?) {
|
||||
guard let root = root else {
|
||||
return
|
||||
}
|
||||
// Visit priority: root node -> left subtree -> right subtree
|
||||
list.append(root.val)
|
||||
preOrder(root: root.left)
|
||||
preOrder(root: root.right)
|
||||
}
|
||||
|
||||
/* Inorder traversal */
|
||||
func inOrder(root: TreeNode?) {
|
||||
guard let root = root else {
|
||||
return
|
||||
}
|
||||
// Visit priority: left subtree -> root node -> right subtree
|
||||
inOrder(root: root.left)
|
||||
list.append(root.val)
|
||||
inOrder(root: root.right)
|
||||
}
|
||||
|
||||
/* Postorder traversal */
|
||||
func postOrder(root: TreeNode?) {
|
||||
guard let root = root else {
|
||||
return
|
||||
}
|
||||
// Visit priority: left subtree -> right subtree -> root node
|
||||
postOrder(root: root.left)
|
||||
postOrder(root: root.right)
|
||||
list.append(root.val)
|
||||
}
|
||||
|
||||
@main
|
||||
enum BinaryTreeDFS {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
/* Initialize binary tree */
|
||||
// Here we use a function to generate a binary tree directly from an array
|
||||
let root = TreeNode.listToTree(arr: [1, 2, 3, 4, 5, 6, 7])!
|
||||
print("\nInitialize binary tree\n")
|
||||
PrintUtil.printTree(root: root)
|
||||
|
||||
/* Preorder traversal */
|
||||
list.removeAll()
|
||||
preOrder(root: root)
|
||||
print("\nPre-order traversal node print sequence = \(list)")
|
||||
|
||||
/* Inorder traversal */
|
||||
list.removeAll()
|
||||
inOrder(root: root)
|
||||
print("\nIn-order traversal node print sequence = \(list)")
|
||||
|
||||
/* Postorder traversal */
|
||||
list.removeAll()
|
||||
postOrder(root: root)
|
||||
print("\nPost-order traversal node print sequence = \(list)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* File: ListNode.swift
|
||||
* Created Time: 2023-01-02
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
public class ListNode: Hashable {
|
||||
public var val: Int // Node value
|
||||
public var next: ListNode? // Successor node reference
|
||||
|
||||
public init(x: Int) {
|
||||
val = x
|
||||
}
|
||||
|
||||
public static func == (lhs: ListNode, rhs: ListNode) -> Bool {
|
||||
lhs.val == rhs.val && lhs.next.map { ObjectIdentifier($0) } == rhs.next.map { ObjectIdentifier($0) }
|
||||
}
|
||||
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(val)
|
||||
hasher.combine(next.map { ObjectIdentifier($0) })
|
||||
}
|
||||
|
||||
public static func arrToLinkedList(arr: [Int]) -> ListNode? {
|
||||
let dum = ListNode(x: 0)
|
||||
var head: ListNode? = dum
|
||||
for val in arr {
|
||||
head?.next = ListNode(x: val)
|
||||
head = head?.next
|
||||
}
|
||||
return dum.next
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* File: Pair.swift
|
||||
* Created Time: 2023-06-28
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Key-value pair */
|
||||
public class Pair: Equatable {
|
||||
public var key: Int
|
||||
public var val: String
|
||||
|
||||
public init(key: Int, val: String) {
|
||||
self.key = key
|
||||
self.val = val
|
||||
}
|
||||
|
||||
public static func == (lhs: Pair, rhs: Pair) -> Bool {
|
||||
lhs.key == rhs.key && lhs.val == rhs.val
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* File: PrintUtil.swift
|
||||
* Created Time: 2023-01-02
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
public enum PrintUtil {
|
||||
private class Trunk {
|
||||
var prev: Trunk?
|
||||
var str: String
|
||||
|
||||
init(prev: Trunk?, str: String) {
|
||||
self.prev = prev
|
||||
self.str = str
|
||||
}
|
||||
}
|
||||
|
||||
public static func printLinkedList(head: ListNode) {
|
||||
var head: ListNode? = head
|
||||
var list: [String] = []
|
||||
while head != nil {
|
||||
list.append("\(head!.val)")
|
||||
head = head?.next
|
||||
}
|
||||
print(list.joined(separator: " -> "))
|
||||
}
|
||||
|
||||
public static func printTree(root: TreeNode?) {
|
||||
printTree(root: root, prev: nil, isRight: false)
|
||||
}
|
||||
|
||||
private static func printTree(root: TreeNode?, prev: Trunk?, isRight: Bool) {
|
||||
if root == nil {
|
||||
return
|
||||
}
|
||||
|
||||
var prevStr = " "
|
||||
let trunk = Trunk(prev: prev, str: prevStr)
|
||||
|
||||
printTree(root: root?.right, prev: trunk, isRight: true)
|
||||
|
||||
if prev == nil {
|
||||
trunk.str = "———"
|
||||
} else if isRight {
|
||||
trunk.str = "/———"
|
||||
prevStr = " |"
|
||||
} else {
|
||||
trunk.str = "\\———"
|
||||
prev?.str = prevStr
|
||||
}
|
||||
|
||||
showTrunks(p: trunk)
|
||||
print(" \(root!.val)")
|
||||
|
||||
if prev != nil {
|
||||
prev?.str = prevStr
|
||||
}
|
||||
trunk.str = " |"
|
||||
|
||||
printTree(root: root?.left, prev: trunk, isRight: false)
|
||||
}
|
||||
|
||||
private static func showTrunks(p: Trunk?) {
|
||||
if p == nil {
|
||||
return
|
||||
}
|
||||
|
||||
showTrunks(p: p?.prev)
|
||||
print(p!.str, terminator: "")
|
||||
}
|
||||
|
||||
public static func printHashMap<K, V>(map: [K: V]) {
|
||||
for (key, value) in map {
|
||||
print("\(key) -> \(value)")
|
||||
}
|
||||
}
|
||||
|
||||
public static func printHeap(queue: [Int]) {
|
||||
print("Heap array representation:", terminator: "")
|
||||
print(queue)
|
||||
print("Heap tree representation:")
|
||||
let root = TreeNode.listToTree(arr: queue)
|
||||
printTree(root: root)
|
||||
}
|
||||
|
||||
public static func printMatrix<T>(matrix: [[T]]) {
|
||||
print("[")
|
||||
for row in matrix {
|
||||
print(" \(row),")
|
||||
}
|
||||
print("]")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* File: TreeNode.swift
|
||||
* Created Time: 2023-01-02
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Binary tree node class */
|
||||
public class TreeNode {
|
||||
public var val: Int // Node value
|
||||
public var height: Int // Node height
|
||||
public var left: TreeNode? // Reference to left child node
|
||||
public var right: TreeNode? // Reference to right child node
|
||||
|
||||
/* Constructor */
|
||||
public init(x: Int) {
|
||||
val = x
|
||||
height = 0
|
||||
}
|
||||
|
||||
// For the serialization encoding rules, please refer to:
|
||||
// https://www.hello-algo.com/chapter_tree/array_representation_of_tree/
|
||||
// Array representation of binary tree:
|
||||
// [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15]
|
||||
// Linked list representation of binary tree:
|
||||
// /——— 15
|
||||
// /——— 7
|
||||
// /——— 3
|
||||
// | \——— 6
|
||||
// | \——— 12
|
||||
// ——— 1
|
||||
// \——— 2
|
||||
// | /——— 9
|
||||
// \——— 4
|
||||
// \——— 8
|
||||
|
||||
/* Deserialize a list into a binary tree: recursion */
|
||||
private static func listToTreeDFS(arr: [Int?], i: Int) -> TreeNode? {
|
||||
if i < 0 || i >= arr.count || arr[i] == nil {
|
||||
return nil
|
||||
}
|
||||
let root = TreeNode(x: arr[i]!)
|
||||
root.left = listToTreeDFS(arr: arr, i: 2 * i + 1)
|
||||
root.right = listToTreeDFS(arr: arr, i: 2 * i + 2)
|
||||
return root
|
||||
}
|
||||
|
||||
/* Deserialize a list into a binary tree */
|
||||
public static func listToTree(arr: [Int?]) -> TreeNode? {
|
||||
listToTreeDFS(arr: arr, i: 0)
|
||||
}
|
||||
|
||||
/* Serialize a binary tree into a list: recursion */
|
||||
private static func treeToListDFS(root: TreeNode?, i: Int, res: inout [Int?]) {
|
||||
if root == nil {
|
||||
return
|
||||
}
|
||||
while i >= res.count {
|
||||
res.append(nil)
|
||||
}
|
||||
res[i] = root?.val
|
||||
treeToListDFS(root: root?.left, i: 2 * i + 1, res: &res)
|
||||
treeToListDFS(root: root?.right, i: 2 * i + 2, res: &res)
|
||||
}
|
||||
|
||||
/* Serialize a binary tree into a list */
|
||||
public static func treeToList(root: TreeNode?) -> [Int?] {
|
||||
var res: [Int?] = []
|
||||
treeToListDFS(root: root, i: 0, res: &res)
|
||||
return res
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* File: Vertex.swift
|
||||
* Created Time: 2023-02-19
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Vertex class */
|
||||
public class Vertex: Hashable {
|
||||
public var val: Int
|
||||
|
||||
public init(val: Int) {
|
||||
self.val = val
|
||||
}
|
||||
|
||||
public static func == (lhs: Vertex, rhs: Vertex) -> Bool {
|
||||
lhs.val == rhs.val
|
||||
}
|
||||
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(val)
|
||||
}
|
||||
|
||||
/* Input value list vals, return vertex list vets */
|
||||
public static func valsToVets(vals: [Int]) -> [Vertex] {
|
||||
vals.map { Vertex(val: $0) }
|
||||
}
|
||||
|
||||
/* Input vertex list vets, return value list vals */
|
||||
public static func vetsToVals(vets: [Vertex]) -> [Int] {
|
||||
vets.map { $0.val }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user