參考題解出處:ikaruga
思路
使用滑動窗口找出所有和爲 target 的子數組
使用 multimap 按照長度保存
使用雙循環依次遍歷兩個不同的子數組
- 如果有交叉跳過,注意是按長度排的,要在前在後都判斷
- 記錄最小值
- 剪枝
class Solution {
public:
int minSumOfLengths(vector<int>& arr, int target) {
multimap<int,int> mp;
int res = INT_MAX;
int left = 0,right = 0,sum = 0;
while (right < arr.size()) {
sum += arr[right];
right++;
if (sum < target) continue;
while (sum > target) {
sum -= arr[left];
left++;
}
if (sum == target) {
mp.insert({ right - left, left });
}
}
for(auto it = mp.begin();it != mp.end();it++){
if (it->first * 2 >= res) break;
auto it2 = it;
while((++it2) != mp.end()){
if(it2->second > it->second && it->second + it->first > it2->second) continue;
if(it->second > it2->second && it2->second + it2->first > it->second)continue;
res = min(res, it->first + it2->first);
}
}
return res == INT_MAX ? -1 : res;
}
};