校招算法笔面试 | 华为机试-合并表记录

题目

题目链接

解题思路

  1. 使用Map数据结构存储index和value的对应关系
  2. 读取输入:
    • 首先读取记录数n
    • 然后读取n行index和value对
  3. 如果遇到相同的index,将value值累加
  4. 最后按index升序输出结果

代码

#include <iostream>
#include <map>
using namespace std;

int main() {
    int n;
    cin >> n;
    
    map<int, int> records;
    
    // 读取输入并合并
    for(int i = 0; i < n; i++) {
        int index, value;
        cin >> index >> value;
        records[index] += value;  // 自动处理重复的index
    }
    
    // 按序输出结果
    for(const auto& pair : records) {
        cout << pair.first << " " << pair.second << endl;
    }
    
    return 0;
}
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        
        // TreeMap自动按键排序
        TreeMap<Integer, Integer> records = new TreeMap<>();
        
        // 读取输入并合并
        for(int i = 0; i < n; i++) {
            int index = sc.nextInt();
            int value = sc.nextInt();
            records.put(index, records.getOrDefault(index, 0) + value);
        }
        
        // 输出结果
        for(Map.Entry<Integer, Integer> entry : records.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }
    }
}
n = int(input())
records = {}

# 读取输入并合并
for _ in range(n):
    index, value = map(int, input().split())
    records[index] = records.get(index, 0) + value

# 按序输出结果
for index in sorted(records.keys()):
    print(index, records[index])

算法及复杂度

  • 算法:使用有序映射表(Map)存储和合并数据
  • 时间复杂度: O ( n log ⁡ n ) \mathcal{O}(n\log n) O(nlogn) - 主要来自Map的插入和排序操作
  • 空间复杂度: O ( k ) \mathcal{O}(k) O(k) - k为不同index的数量,最坏情况下为n
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值