笔试编程题

1、题目:简单图像压缩 描述: 你正在开发一个基础的图像压缩算法。给定一个表示灰度图像的二维整数矩阵,中每个像素的灰度值范围 是0-255。你的任务是实现一个简单的压缩算法,将相邻的相同值像素组合在一起,以减少存储空间。 要求:

实现函数vector <vector < pair <int, int>> > compresslmage(const vector<vector<int> > & image)

输入参数image是一个示灰度图像的二维整数矩阵 返回值应该是一个压缩后的数据结构,其中每个元素是一个pair<int, int>,示(像素值,连续出现的次数) 压缩应该在每一行内进行,不跨行压缩 考虑输入为空或只有-行/-列的情况 优化算法以处理大型图像(如4K分辨率)

示例:

输入:

[

    [1, 1, 2, 2, 2],

    [3, 3, 3, 4, 4],

    [5, 5, 5, 5, 5]

]

输出:

[

    [[1, 2], [2, 3]],

    [[3, 3], [4, 2]],

    [[5, 5]]

]

#include <vector>  
#include <utility> // for std::pair  
#include<iostream>
using namespace std;
vector<vector<pair<int, int>>> compressImage(const vector<vector<int>>& image) {
    vector<vector<pair<int, int>>> compressed;
    // 检查输入是否为空  
    if (image.empty()) return compressed;
    // 遍历每一行  
    for (const auto& row : image) {
        vector<pair<int, int>> currentRow;
        if (row.empty()) {
            // 如果当前行为空,则添加一个空的压缩结果  
            compressed.push_back(currentRow);
            continue;
        }
        int currentValue = row[0];
        int count = 1;
        // 遍历当前行的每个像素  
        for (size_t i = 1; i < row.size(); ++i) {
            if (row[i] == currentValue) {
                // 如果当前像素与前一个像素相同,则增加计数  
                ++count;
            }
            else {
                // 如果不同,则将当前值和计数添加到结果中,并重置计数器和当前值  
                currentRow.push_back(make_pair(currentValue, count));
                currentValue = row[i];
                count = 1;
            }
        }
        // 将最后一组值和计数添加到结果中  
        currentRow.push_back(make_pair(currentValue, count));
        compressed.push_back(currentRow);
    }
    return compressed;
}
int main() {
    vector<vector<int>> image = {
        {1, 1, 2, 2, 2},
        {3, 3, 3, 4, 4},
        {5, 5, 5, 5, 5}
    };

    vector<vector<pair<int, int>>> compressedImage = compressImage(image);

    // 打印结果  
    for (const auto& row : compressedImage) {
        for (const auto& pair : row) {
            cout << "[" << pair.first << ", " << pair.second << "] ";
        }
        cout << endl;
    }

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值