HJ8 合并表记录

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/ )
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/15553317.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

描述

数据表记录包含表索引和数值(int范围的正整数),请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照key值升序进行输出。
 
提示:
0 <= index <= 11111111
1 <= value <= 100000

输入描述:

先输入键值对的个数n(1 <= n <= 500)
然后输入成对的index和value值,以空格隔开

输出描述:

输出合并后的键值对(多行)

示例1

输入:
4
0 1
0 2
1 2
3 4
输出:
0 3
1 2
3 4

示例2

输入:
3
0 1
0 2
8 9
输出:
0 3
8 9
let count = Int(readLine() ?? "") ?? 0
var list: [Int] = [Int](repeatElement(0, count: count))
calculate(count)

func calculate(_ count: Int) {
    for i in 0..<count {
        let input = readLine() ?? ""
        let array = input.split(separator: " ")
        let index = Int(array.first ?? "") ?? 0
        let value = Int(array.last ?? "") ?? 0
        list[index] += value
    }
    
    for i in 0..<count {
        if (list[i] != 0) {
            print("\(i) \(list[i])")
        }
    }
}
import Foundation

let count = Int(readLine()!)!
var dic = [Int : Int]()
for _ in 0..<count {
    let parts = readLine()!.split(separator: " ")
    let key = Int(parts[0])!
    let value = Int(parts[1])!
    if let result = dic[key] {
        dic[key] = result + value
    } else {
        dic[key] = value
    }
}
let keys = dic.keys.sorted() { $0 < $1 }
for key in keys {
    print("\(key) \(dic[key]!)")
}
原文地址:https://www.cnblogs.com/strengthen/p/15553317.html