给定n个数,找到一个最大区间使得区间内所有数的和能被n整除,用c++给出代码
时间: 2024-04-15 09:31:29 浏览: 72
以下是用C++实现的代码示例:
```cpp
#include <iostream>
#include <vector>
#include <unordered_map>
std::pair<int, int> findMaxInterval(std::vector<int>& arr, int n) {
std::vector<int> prefixSum(arr.size() + 1, 0);
for (int i = 1; i <= arr.size(); i++) {
prefixSum[i] = (prefixSum[i - 1] + arr[i - 1]) % n;
}
int maxLength = 0;
int intervalStart = 0;
int intervalEnd = 0;
std::unordered_map<int, int> prefixSumHash;
for (int i = 0; i < prefixSum.size(); i++) {
if (prefixSum[i] == 0) {
maxLength = i;
intervalStart = 0;
intervalEnd = i - 1;
} else if (prefixSumHash.count(prefixSum[i])) {
if (i - prefixSumHash[prefixSum[i]] > maxLength) {
maxLength = i - prefixSumHash[prefixSum[i]];
intervalStart = prefixSumHash[prefixSum[i]] + 1;
intervalEnd = i - 1;
}
} else {
prefixSumHash[prefixSum[i]] = i;
}
}
return std::make_pair(intervalStart, intervalEnd);
}
int main() {
std::vector<int> arr = {4, 3, 1, 6, 7};
int n = 3;
std::pair<int, int> result = findMaxInterval(arr, n);
int start = result.first;
int end = result.second;
std::cout << "最大区间起始索引: " << start << std::endl;
std::cout << "最大区间结束索引: " << end << std::endl;
return 0;
}
```
这段代码也是基于前缀和的思想,使用了unordered_map来保存前缀和和其对应的索引。时间复杂度为O(n),其中n是给定数组的长度。
阅读全文