ARTICLE DETAIL

资讯详情

深耕编程入门与网站建设的一线实战洞察。

leetcode 1712. Ways to Split Array Into Three Subarrays

leetcode 1712. Ways to Split Array Into Three Subarrays Problem: 1712. 将数组分成三个子数组的方案数前缀和后缀和双指针第一个指针是i第二个指针是23部分累加和的一半的位置也就是rem prefix.back() - prefix[i], half (rem / 2) (((rem%2) 0)? 0:1);此时第二个指针ind0指向可能的最右侧累加两个指针的距离就行, 第一个指针ind1指向可能的最左侧ind0 lower_bound(after.begin(), after.end(), half) - after.begin();特殊情况是全0Codeclass Solution { public: const int mod 1e9 7; int waysToSplit(vectorint nums) { vectorint prefix{0}, after{0}; int n nums.size(), zero 0; for(int i 0; i n; i) { prefix.push_back(prefix.back() nums[i]); } for(int i n-1; i 0; i--) { after.push_back(after.back() nums[i]); } after.erase(after.begin()); unsigned long long sum 0; int ind0, ind1, now, rem, half; for(int i 1; i n; i) { now prefix[i]; rem prefix.back() - now; if(rem now * 2) continue; half (rem / 2) (((rem%2) 0)? 0:1); ind0 lower_bound(after.begin(), after.end(), half) - after.begin(); ind0 n - ind0; ind1 lower_bound(prefix.begin() i 1, prefix.end(), now * 2) - prefix.begin(); if(ind0 n) { while(prefix[ind0] - now prefix.back() - prefix[ind0]) ind0--; while(ind1 n prefix[ind1] - now now) ind1; if(ind0 ind1) { sum ind0 - ind1 1; if(prefix[ind0] 0 prefix.back() - prefix[ind0]0) sum--; sum sum % mod; } } } return sum % mod; } };
返回列表