From f0600e560e72186b6a31e2a0735874d56e34b381 Mon Sep 17 00:00:00 2001 From: Lanre Adedara Date: Wed, 30 Oct 2024 08:33:01 +0100 Subject: [PATCH] feat: add swift implementation to lcof2 problem: No.111 --- .../README.md" | 66 +++++++++++++++++++ .../Solution.swift" | 61 +++++++++++++++++ 2 files changed, 127 insertions(+) create mode 100644 "lcof2/\345\211\221\346\214\207 Offer II 111. \350\256\241\347\256\227\351\231\244\346\263\225/Solution.swift" diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 111. \350\256\241\347\256\227\351\231\244\346\263\225/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 111. \350\256\241\347\256\227\351\231\244\346\263\225/README.md" index 50e3b501799b6..1cfbb8313ebe9 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 111. \350\256\241\347\256\227\351\231\244\346\263\225/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 111. \350\256\241\347\256\227\351\231\244\346\263\225/README.md" @@ -292,6 +292,72 @@ func find(x int) int { } ``` +#### Swift + +```swift +class Solution { + private var parent = [Int]() + private var weight = [Double]() + + func calcEquation( + _ equations: [[String]], + _ values: [Double], + _ queries: [[String]] + ) -> [Double] { + let n = equations.count + parent = Array(0..<(n * 2)) + weight = Array(repeating: 1.0, count: n * 2) + + var map = [String: Int]() + var index = 0 + + for i in 0.. Int { + if parent[x] != x { + let origin = parent[x] + parent[x] = find(parent[x]) + weight[x] *= weight[origin] + } + return parent[x] + } +} +``` + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 111. \350\256\241\347\256\227\351\231\244\346\263\225/Solution.swift" "b/lcof2/\345\211\221\346\214\207 Offer II 111. \350\256\241\347\256\227\351\231\244\346\263\225/Solution.swift" new file mode 100644 index 0000000000000..084ab48d48fd5 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 111. \350\256\241\347\256\227\351\231\244\346\263\225/Solution.swift" @@ -0,0 +1,61 @@ +class Solution { + private var parent = [Int]() + private var weight = [Double]() + + func calcEquation( + _ equations: [[String]], + _ values: [Double], + _ queries: [[String]] + ) -> [Double] { + let n = equations.count + parent = Array(0..<(n * 2)) + weight = Array(repeating: 1.0, count: n * 2) + + var map = [String: Int]() + var index = 0 + + for i in 0.. Int { + if parent[x] != x { + let origin = parent[x] + parent[x] = find(parent[x]) + weight[x] *= weight[origin] + } + return parent[x] + } +} \ No newline at end of file