求助丨这一题我不会,请问下可以教下我吗
1007
2024.08.03
2024.08.05
发布于 四川

降低时间复杂度

在C++中给定一个数组,要求按照相邻元素必须大于3拆分成很多个数组,要保证拆分的数组最少。

输入:[1,1,2,2,2,3,3,3,4,6,8,10]
输出:[1,8] [1,6,10] [2] [2] [2] [3] [3] [3] [4]

#include <iostream>
#include <vector>

std::vector<std::vector<int>> splitArray(const std::vector<int>& arr) {
    std::vector<std::vector<int>> result;
    if (arr.empty()) return result;

    // Start with the first element
    result.push_back({arr[0]});

    for (size_t i = 1; i < arr.size(); ++i) {
        bool added = false;
        // Try to find the appropriate subarray to insert the element
        for (size_t j = 0; j < result.size(); ++j) {
            if (arr[i] - result[j].back() > 3) {
                result[j].push_back(arr[i]);
                added = true;
                break;
            }
        }
        // If no suitable subarray was found, create a new one
        if (!added) {
            result.push_back({arr[i]});
        }
    }

    return result;
}

int main() {
    std::vector<int> arr = {1, 1, 2, 2, 2, 3, 3, 3, 4, 6, 8, 10};
    std::vector<std::vector<int>> result = splitArray(arr);

    for (const auto& group : result) {
        for (int num : group) {
            std::cout << num << " ";
        }
        std::cout << std::endl;
    }

    return 0;
}
评论 (14)