Skip to content

Commit 36e83e7

Browse files
committed
practice to solve no.3583. Count Special Triplets
1 parent 352194d commit 36e83e7

1 file changed

Lines changed: 25 additions & 24 deletions

File tree

javascript/index.js

Lines changed: 25 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -998,33 +998,32 @@ var smallestRepunitDivByK = function(k) {
998998
* @return {number}
999999
*/
10001000
var specialTriplets = function(nums) {
1001-
let ans = 0;
1002-
// j as the middle of the triplet.
1003-
// For each j, you only need:
1004-
// how many values equal to 2 * nums[j] appear before j
1005-
// how many appear after j
1006-
// Then the contribution from index j is just:
1007-
// leftCount * rightCount
1008-
// let j = Math.floor(nums[nums.length % 2 ]);
1009-
// // console.log(j)
1010-
// for(let i = 0;i < nums.length;++i) {
1011-
1012-
// }
1013-
1014-
/**
1001+
/*
1002+
* j as the middle of the triplet.
1003+
* For each j, you only need:
1004+
* how many values equal to 2 * nums[j] appear before j
1005+
* how many appear after j
1006+
* Then the contribution from index j is just:
1007+
* leftCount * rightCount
1008+
*
10151009
* j = middle index
10161010
* 在j之前,檢查nums[i] === nums[j] * 2 的有幾個
10171011
* 在j之後,檢查nums[k] === nums[j] * 2 的有幾個
10181012
*/
1019-
// let left = new Map();
1020-
// let right = new Map();
1021-
let j = Math.round(nums.length % 2);
1022-
for(let i = 0;i < nums.length;++i) {
1023-
if(nums[i] === nums[j] * 2 && i < j){
1024-
ans++;
1025-
}
1026-
}
1027-
console.log(ans)
1013+
1014+
// Use frequency arrays or maps, e.g. freqPrev and freqNext—to track how many times each value appears before and after the current index.
1015+
// For each index j in the triplet (i,j,k), compute its contribution to the answer using your freqPrev and freqNext counts.
1016+
let ans = 0;
1017+
let freqPrev = new Map() , freqNext = new Map();
1018+
const MOD = 1e9 + 7;
1019+
for(const element of nums){
1020+
freqPrev.set(element, freqPrev.get(element) || 0 + 1);
1021+
}
1022+
for(let i = 0;i < nums.length;++i) {
1023+
1024+
}
1025+
return ans;
1026+
10281027
};
10291028
// let nums = [8,4,2,8,4];
10301029
/**
@@ -1041,7 +1040,9 @@ var specialTriplets = function(nums) {
10411040
* nums[1] = nums[2] * 2 = 2 * 2 = 4
10421041
* nums[4] = nums[2] * 2 = 2 * 2 = 4
10431042
*/
1044-
// console.log(specialTriplets(nums));
1043+
let nums = [0,1,0,0];
1044+
// 1
1045+
console.log(specialTriplets(nums));
10451046

10461047

10471048
/**

0 commit comments

Comments
 (0)