1. 程式人生 > 其它 >牛客華為機試HJ8

牛客華為機試HJ8

原題傳送門

1. 問題描述

2. Solution

1、思路分析
用TreeMap儲存讀到到每個 index value對,index放入TreeMap是自動按index大小排序的,對於value的話,先取出上次的值,再把本次讀到的value累加上去。

2、程式碼實現
Java實現

package huawei.HJ008;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

public class Main {
    static Scanner in;

    public static void main(String[] args) throws IOException {
        if (!"Linux".equals(System.getProperty("os.name"))) {
            in = new Scanner(Paths.get("/Users/jun/Learn/JavaLearning/NowCoder/src/huawei/HJ008/input.txt"));
        } else {
            in = new Scanner(System.in);
        }
        while (in.hasNext()) {
            int n = in.nextInt();
            solve(n);
        }
    }

    private static void solve(int n) {
        TreeMap<Integer, Integer> map = new TreeMap<>();
        for (int i = 0; i < n; i++) {
            int index = in.nextInt();
            int value = in.nextInt();
            map.put(index, map.getOrDefault(index, 0) + value);
        }
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }
    }
}

Python實現

import sys

if sys.platform != "linux":
    sys.stdin = open("input/HJ8.txt")

n = int(input().strip())
d = dict()
for line in sys.stdin:
    idx, val = map(int, line.strip().split())
    if idx not in d:
        d[idx] = val
    else:
        d[idx] += val

result = sorted(list(d.items()), key=lambda x: x[0])
for idx, val in result:
    print(f'{idx} {val}')

3、複雜度分析
時間複雜度: O(n)
空間複雜度: O(n)