美文网首页
两个有序数组合并成一个有序数组

两个有序数组合并成一个有序数组

作者: CocoaJason | 来源:发表于2020-12-10 14:02 被阅读0次
    extension ViewController {
        func mergeOrderArray(With firstAry: Array<String>,
                             secondAry: Array<String>) -> Array<String> {
            
            var FirstAry = firstAry
            var SecondAry = secondAry
            if FirstAry.isEmpty &&
                SecondAry.isEmpty{
                return []
            }
            
            if FirstAry.isEmpty {
                return SecondAry
            }
            
            if secondAry.isEmpty {
                return FirstAry
            }
            
            var endAry = [String]()
            
            while true {
                if Int(FirstAry.first!) ?? 0 < Int(SecondAry.first!) ?? 0 {
                    endAry.append(FirstAry.first!)
                    FirstAry.removeFirst()
                } else {
                    endAry.append(SecondAry.first!)
                    SecondAry.removeFirst()
                }
                
                if FirstAry.isEmpty {
                    endAry.append(contentsOf: SecondAry)
                    break
                }
                
                if SecondAry.isEmpty {
                    endAry.append(contentsOf: FirstAry)
                    break
                }
            }
        
            return endAry
        }
    }
    
    
    print(mergeOrderArray(With: ["1","3","5","7","9"],
                                  secondAry: ["1","2","17","20","35"]))
    

    打印结果

    ["1", "1", "2", "3", "5", "7", "9", "17", "20", "35"]
    

    相关文章

      网友评论

          本文标题:两个有序数组合并成一个有序数组

          本文链接:https://www.haomeiwen.com/subject/bfzlgktx.html