華為OD機(jī)試真題2023_Swift_100_關(guān)聯(lián)端口組合并

// 關(guān)聯(lián)端口組合并
    func HW2023009() {
        var inputArr: [String] = []
        // 測(cè)試用例
//        let M = 9
//        inputArr = ["4","2,3,2","1,2","5"]
//        inputArr = ["2,3,1","4,3,2","5"]
//        inputArr = ["10","4,2,1","9","3,6,9,2","6,3,4","8"]
        // 開(kāi)始代碼
        let M = Int(readLine()!)!
        while let line = readLine() {
            inputArr.append(line)
        }
        if M > 10 { // 超過(guò)端口組數(shù)10的一律打印"[[]]"
            print("[[]]")
        }else {
            var res: [Set<String>] = [] // 端口數(shù)組集合
            for i in inputArr {
                let set: Set<String> = Set(i.components(separatedBy: ","))  // 生成要進(jìn)行合并的端口集合set
                res.append(set) // 將端口集合set直接添加到res
                if set.count != 1 { // 如果端口集合set的元素個(gè)數(shù)大于1,則需要檢查是否需要合并該集合
                    hebing(set, &res, res.count-1)
                }
            }
            
            var resStr: [String] = []
            for i in res {
                // 由于前面集合里面的沒(méi)有排序,所以這里先排序再拼接
                let temp = Array(i.map { String($0)}).sorted().joined(separator: ",")
                resStr.append("[\(temp)]")
            }
            let temp = resStr.joined(separator: ",")
            print("[\(temp)]") // 打印最終結(jié)果
        }
    }
    // set:要進(jìn)行合并的端口集合 res:端口數(shù)組集合 index:需要進(jìn)行合并的集合下標(biāo)
    func hebing(_ set: Set<String>, _ res: inout [Set<String>], _ index: Int) {
        var setUnion: Set<String> = [] // 合并后的集合
        for (i,setIndex) in res.enumerated() {
            if i == index { // 因?yàn)閞es已經(jīng)添加了set,所以當(dāng)遍歷到時(shí)直接跳過(guò)
                continue
            }
            if set.intersection(setIndex).count >= 2 { // 要進(jìn)行合并的端口集合set與端口數(shù)組集合中遍歷出來(lái)的的元素setIndex取交集,如果交集個(gè)數(shù)大于2,則需要進(jìn)行合并
                setUnion = set.union(setIndex) // 要進(jìn)行合并的端口集合set與端口數(shù)組集合中遍歷出來(lái)的的元素setIndex取并集setUnion
                let beforeIndex = index > i ? i : index // 求出排在前面的下標(biāo)
                let afterIndex = index > i ? index : i // 再求排在后面的下標(biāo)
                res.remove(at: afterIndex) // 先移除后面的集合
                res.remove(at: beforeIndex) // 再移除前面的集合
                res.insert(setUnion, at: beforeIndex) // 再插入合并后的合集到前面的下標(biāo)位置
                hebing(setUnion, &res, beforeIndex)// 將合并后的合集在進(jìn)行合并判斷,看是否需要再次進(jìn)行合并
            }
        }
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容