classSolution: defcountQuadruplets(self, nums: List[int]) -> int: n = len(nums) great = [0] * n great[-1] = [0] * (n + 1) for k inrange(n - 2, 1, -1): great[k] = great[k + 1][:] for x inrange(1, nums[k + 1]): great[k][x] += 1# x < nums[k+1],对于 x,大于它的数的个数 +1
ans = 0 less = [0] * (n + 1) for j inrange(1, n - 1): for x inrange(nums[j - 1] + 1, n + 1): less[x] += 1# x > nums[j-1],对于 x,小于它的数的个数 +1 for k inrange(j + 1, n - 1): if nums[j] > nums[k]: ans += less[nums[k]] * great[k][nums[j]] return ans
classSolution { int great[4000][4001]; public: longlongcountQuadruplets(vector<int> &nums){ int n = nums.size(), less[n + 1]; for (int k = n - 2; k >= 2; k--) { memcpy(great[k], great[k + 1], sizeof(great[k + 1])); for (int x = nums[k + 1] - 1; x > 0; x--) great[k][x]++; // x < nums[k+1],对于 x,大于它的数的个数 +1 }
long ans = 0; memset(less, 0, sizeof(less)); for (int j = 1; j < n - 2; j++) { for (int x = nums[j - 1] + 1; x <= n; x++) less[x]++; // x > nums[j-1],对于 x,小于它的数的个数 +1 for (int k = j + 1; k < n - 1; k++) if (nums[j] > nums[k]) ans += less[nums[k]] * great[k][nums[j]]; } return ans; } };
classSolution: defcountQuadruplets(self, nums: List[int]) -> int: n = len(nums) great = [0] * n great[-1] = [0] * (n + 1) for k inrange(n - 2, 0, -1): great[k] = great[k + 1][:] for x inrange(1, nums[k + 1]): great[k][x] += 1
ans = 0 for j inrange(1, n - 1): for k inrange(j + 1, n - 1): x = nums[k] if nums[j] > x: ans += (x - n + 1 + j + great[j][x]) * great[k][nums[j]] return ans
classSolution { publiclongcountQuadruplets(int[] nums) { intn= nums.length; int[][] great = newint[n][n + 1]; for (intk= n - 2; k > 0; k--) { great[k] = great[k + 1].clone(); for (intx= nums[k + 1] - 1; x > 0; x--) great[k][x]++; }
longans=0; for (intj=1; j < n - 2; j++) for (intk= j + 1; k < n - 1; k++) { intx= nums[k]; if (nums[j] > x) ans += (x - n + 1 + j + great[j][x]) * great[k][nums[j]]; } return ans; } }
[sol2-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { int great[4000][4001]; public: longlongcountQuadruplets(vector<int> &nums){ int n = nums.size(); for (int k = n - 2; k; k--) { memcpy(great[k], great[k + 1], sizeof(great[k + 1])); for (int x = nums[k + 1] - 1; x > 0; x--) great[k][x]++; }
long ans = 0; for (int j = 1; j < n - 2; j++) for (int k = j + 1; k < n - 1; k++) if (int x = nums[k]; nums[j] > x) ans += (x - n + 1 + j + great[j][x]) * great[k][nums[j]]; return ans; } };
funccountQuadruplets(nums []int) (ans int64) { n := len(nums) great := make([][]int, n) great[n-1] = make([]int, n+1) for k := n - 2; k > 0; k-- { great[k] = append([]int(nil), great[k+1]...) for x := nums[k+1] - 1; x > 0; x-- { great[k][x]++ } }
for j := 1; j < n-2; j++ { for k := j + 1; k < n-1; k++ { x := nums[k] if nums[j] > x { ans += int64((x - n + 1 + j + great[j][x]) * great[k][nums[j]]) } } } return }