面试题答案
一键面试#include <iostream>
#include <vector>
// 压缩函数
std::vector<char> compress(const std::vector<int>& data) {
std::vector<char> compressed;
char currentByte = 0;
int bitIndex = 0;
for (int num : data) {
for (int i = 0; i < 8 && bitIndex < 8; ++i, ++bitIndex) {
currentByte |= ((num >> i) & 1) << bitIndex;
if (bitIndex == 7) {
compressed.push_back(currentByte);
currentByte = 0;
bitIndex = 0;
}
}
}
if (bitIndex > 0) {
compressed.push_back(currentByte);
}
return compressed;
}
// 解压缩函数
std::vector<int> decompress(const std::vector<char>& compressed) {
std::vector<int> decompressed;
int currentInt = 0;
int bitIndex = 0;
for (char byte : compressed) {
for (int i = 0; i < 8 && bitIndex < 8; ++i, ++bitIndex) {
currentInt |= ((byte >> i) & 1) << bitIndex;
if (bitIndex == 7) {
decompressed.push_back(currentInt);
currentInt = 0;
bitIndex = 0;
}
}
}
if (bitIndex > 0) {
decompressed.push_back(currentInt);
}
return decompressed;
}
复杂度分析
- 时间复杂度:
- 压缩函数:对于
compress
函数,它遍历输入数组中的每个整数,每个整数最多处理8位。因此,时间复杂度为$O(n)$,其中n
是输入数组data
的大小。 - 解压缩函数:对于
decompress
函数,它遍历压缩后的字节数组,每个字节最多处理8位。因此,时间复杂度也为$O(m)$,其中m
是压缩后数组compressed
的大小。在理想情况下,m
小于n
,但最坏情况下,m
可能与n
相近(例如数据本身就无法有效压缩),所以整体时间复杂度还是$O(n)$。
- 压缩函数:对于
- 空间复杂度:
- 压缩函数:
compress
函数创建了一个新的std::vector<char>
来存储压缩后的数据。在最坏情况下,压缩后的数据大小可能接近原始数据大小(例如数据无法有效压缩时),所以空间复杂度为$O(n)$。 - 解压缩函数:
decompress
函数创建了一个新的std::vector<int>
来存储解压缩后的数据。其空间复杂度为$O(n)$,因为解压缩后的数据大小与原始输入数据大小相同。
- 压缩函数:
总体而言,压缩和解压缩函数的时间复杂度和空间复杂度均为$O(n)$。