青训营 X 豆包MarsCode 技术训练营-28. 打点计数器

200 阅读1分钟

问题描述

小明想发明一台打点计数器,这个计数器有这样的一个功能:

  • 它可以接收一个递增的数据范围(形如[3, 9]),其中第一个数字代表起始,第二个数字代表结束

  • 这个数据范围中包含几个数字,打点计数器就会打几个点

  • 在传入的多组数据范围中,如果出现了范围的重复,机器则不会重复打点

你可以帮助小明算一算,在不同的情况下,计数器会打出几个点么?

输入格式

一个二维数组

输出格式

一个整数,表达在输入是这个数组的情况下,计数器打出的点数

输入样例(1)

[ [1,4], [7, 10], [3, 5] ]

输出样例(1)

7

输入样例(2)

[ [1,2], [6, 10], [11, 15] ]

输出样例(2)

9

数据范围

  • 数字范围 [-10^9, 10^9],数组长度 < 2^16
#include <iostream>
#include <vector>
#include <algorithm>
#include <set>

int solution(std::vector<std::vector<int>>& inputArray) {
    if (inputArray.empty()) return 0;

    std::sort(inputArray.begin(), inputArray.end());
    
    std::set<int> points;
    
    for (const auto& interval : inputArray) {
        for (int i = interval[0]; i < interval[1]; ++i) {
            points.insert(i);
        }
    }
    
    return points.size();
}

int main() {
    //  You can add more test cases here
    std::vector<std::vector<int>> testArray1 = {{1, 4}, {7, 10}, {3, 5}};
    std::vector<std::vector<int>> testArray2 = {{1, 2}, {6, 10}, {11, 15}};

    std::cout << (solution(testArray1) == 7) << std::endl;
    std::cout << (solution(testArray2) == 9) << std::endl;

    return 0;
}