# 最接近零的子数组和

``给定一个整数数组，找到一个和最接近于零的子数组。返回第一个和最有一个指数。你的代码应该返回满足要求的子数组的起始位置和结束位置``
``````    struct Node {
int end;
int val;
Node(int e, int v) : end(e), val(v) {}
};
static bool cmp(const Node& a, const Node& b) {
return a.val < b.val;
}``````
``````class Solution {
public:
vector<int> subarraySumClosest(const vector<int>& nums){

vector<Node> vec;
if (nums.empty()) {
return {};
}
int sum = 0;
for (int i = 0; i < nums.size(); ++i) {
sum += nums[i];
vec.push_back(Node(i, sum));
}

sort(vec.begin(), vec.end(), cmp);``````
``````// key point
int min_dif = INT_MAX;
for (int i = 0; i < vec.size(); ++i) {
min_dif = min(abs(vec.front().val), min_dif);
if (i) {
min_dif = min(min_dif, abs(vec[i].val - vec[i - 1].val));
}
}``````
``````vector<int> res;

for (int i = 0; i < vec.size(); ++i) {
if (abs(vec[i].val) == min_dif) {
res.push_back(0);
res.push_back(vec[i].end);
break;
}
if (i && abs(vec[i].val - vec[i - 1].val) == min_dif) {
if (vec[i].end < vec[i - 1].end) {
res.push_back(vec[i].end + 1);
res.push_back(vec[i - 1].end);
}
else {
res.push_back(vec[i - 1].end + 1);
res.push_back(vec[i].end);
}
break;
}
}
cout << min_dif << endl;
return res;
}
};``````

18 人关注
107 篇文章