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