编写出完整C++代码
时间: 2024-10-18 15:11:07 浏览: 11
良心出品C++语言编写的迷宫-完整代码.doc
当然,下面是完整的C++代码,实现了上面描述的算法:
```cpp
#include <iostream>
#include <vector>
using namespace std;
int smallestDifference(vector<int>& A, int K) {
int n = A.size();
if (n == 0) // 处理空数组的情况
return 0;
int max_val = A[0] + K, min_val = A[0] - K;
int prev_diff = max_val - min_val;
for (int i = 1; i < n; ++i) {
// 根据当前元素调整区间
if (A[i] >= max_val)
max_val = A[i] + K;
else if (A[i] <= min_val)
min_val = A[i] - K;
// 计算新差值并更新最小差
int diff = max_val - min_val;
if (diff < prev_diff)
prev_diff = diff;
}
return prev_diff;
}
int main() {
vector<int> A = {5, 10, 15, 20, 25};
int K = 3;
cout << "Smallest difference with a shift of " << K << " is: " << smallestDifference(A, K) << endl;
return 0;
}
```
这段代码定义了一个名为`smallestDifference`的函数,接收一个整数向量`A`和一个整数`K`作为输入,然后返回使得`A`经过加减`K`后的数组B中最大值和最小值差值最小的结果。在`main`函数中,我们提供了一个测试用例,你可以根据需要替换它。
阅读全文