Count Increasing Quadruplets
Count Increasing Quadruplets
Given a 0-indexed integer array nums of size containing all numbers from to , return the number of increasing quadruplets.
A quadruplet (i, j, k, l) is increasing if:
- , and
- .
Example 1:
Input: nums = [1,3,2,4,5] Output: 2 Explanation: - When i = 0, j = 1, k = 2, and l = 3, nums[i] < nums[k] < nums[j] < nums[l]. - When i = 0, j = 1, k = 2, and l = 4, nums[i] < nums[k] < nums[j] < nums[l]. There are no other quadruplets, so we return 2.
Example 2:
Input: nums = [1,2,3,4] Output: 0 Explanation: There exists only one quadruplet with i = 0, j = 1, k = 2, l = 3, but since nums[j] < nums[k], we return 0.
Constraints:
- All the integers of nums are unique. nums is a permutation.
解题思路
一开始看错题了以为是求,这个直接用树状数组就可以实现了,参考三元组。
然后想了一下不会是枚举和吧,结果正解就是这样做,但自己没想出来。
暴力枚举和,在满足的前提下,找到所有小于的且满足,和找到所有大于的且满足,参考下面的示意图:
因此为了在枚举和的时候能够快速统计出来满足且的的数量,和满足且的的数量,这里可以先开个数组表示下标为且的数量,然后对求二维前缀和,然后根据乘法原理将两部分的元素数目相乘得到答案。
然而前缀和数组只能得到下标小于等于且值小于等于的元素数量,那么如何根据来求得下标大于且值大于的元素数量呢?也就是下图的部分:
很简单,只要根据的定义减去白色的部分就行了,具体公式为 。
AC代码如下,时间复杂度为:
1 class Solution { 2 public: 3 long long countQuadruplets(vector<int>& nums) { 4 int n = nums.size(); 5 vector<vector<int>> s(n + 1, vector<int>(n + 1)); 6 for (int i = 1; i <= n; i++) { 7 s[i][nums[i - 1]]++; // 统计数量 8 } 9 for (int i = 1; i <= n; i++) { // 求前缀和 10 for (int j = 1; j <= n; j++) { 11 s[i][j] += s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1]; 12 } 13 } 14 long long ret = 0; 15 for (int i = 1; i <= n; i++) { 16 for (int j = i + 1; j <= n; j++) { 17 if (nums[i - 1] > nums[j - 1]) { 18 ret += 1ll * s[i - 1][nums[j - 1] - 1] * (s[n][n] - s[j][n] - s[n][nums[i - 1]] + s[j][nums[i - 1]]); // 两部分相乘 19 } 20 } 21 } 22 return ret; 23 } 24 };
参考资料
转化思路 前后缀分解【力扣周赛 330】:https://www.bilibili.com/video/BV1mD4y1E7QK/
本文来自博客园,作者:onlyblues,转载请注明原文链接:https://www.cnblogs.com/onlyblues/p/17087208.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效