力扣 第28場雙週賽第3題(滑動窗口) 找兩個和爲目標值且不重疊的子數組

在這裏插入圖片描述
在這裏插入圖片描述
參考題解出處:ikaruga
思路
使用滑動窗口找出所有和爲 target 的子數組
使用 multimap 按照長度保存
使用雙循環依次遍歷兩個不同的子數組

  1. 如果有交叉跳過,注意是按長度排的,要在前在後都判斷
  2. 記錄最小值
  3. 剪枝
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;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章