华为OD机试真题2023_Swift_100_找数字

2023-03-19  本文已影响0人  雾中探雪
// 找数字
    func HW2023024() {
        // 测试用例
//        n = 3
//        m = 5
//        strings = [["0","3","5","4","2"], ["2","5","7","8","3"], ["2","5","4","2","4"]]
        //  开始代码
        n = Int(readLine()!)!
        m = Int(readLine()!)!
        while let line = readLine() {
            let num = line.components(separatedBy: " ")
            if num.count > 0 {
                strings.append(num)
            }
        }
        // mapDic: 将数字和坐标转化为字典 key: 输入的数字字符串 value: 输入的数字坐标
        var mapDic: [String: [[Int]]] = [:]
        for i in 0..<n {
            for j in 0..<m {
                let input = strings[i][j]
                var tempList: [[Int]] = []
                tempList = mapDic.keys.contains(input) ? mapDic[input]! : []
                tempList.append([i,j])
                mapDic.updateValue(tempList, forKey: input)
            }
        }
        var resList: [String] = [] // 结果串
        for i in 0..<n {
            var list: [String] = []
            for j in 0..<m {
                let input = strings[i][j]
                let tempList: [[Int]] = mapDic[input] ?? []
                if tempList.count == 1 { // 只有一个坐标不存在相等值
                    list.append("-1")
                    continue
                }
                var minValue = Int.max // 最小距离
                for num in tempList {
                    let distance = abs(num[0]-i) + abs(num[1]-j)
                    if distance == 0 {  // 距离为零则跳过
                        continue
                    }
                    minValue = min(minValue, distance)
                }
                list.append(String(minValue))
            }
            resList.append("[\(list.joined(separator: ","))]")
        }
        print("[\(resList.joined(separator: ","))]")
    }
上一篇 下一篇

猜你喜欢

热点阅读