1
+ /**
2
+ * Problem 1: Given an array A has n elements.
3
+ * A (L, r, k) query is a query counts # elements equal to k from L to r
4
+ */
5
+
6
+ function main ( A ) {
7
+ if ( A . length === 0 ) return ;
8
+
9
+ function solution ( L , R , K ) {
10
+ let count = 0 ;
11
+ for ( let i = L ; i <= R ; i ++ ) {
12
+ if ( A [ i ] === K ) count ++ ;
13
+ }
14
+
15
+ return count ;
16
+ }
17
+
18
+ return solution ( 3 , 9 , 3 ) ; // test
19
+ }
20
+
21
+ /**
22
+ * Problem 2: Given an array A has n elements.
23
+ * There are #Q queries (L_i, R_i, k) 1 <= i <= Q
24
+ */
25
+
26
+ function main2 ( A ) {
27
+ if ( A . length === 0 ) return ;
28
+
29
+ function solution ( Q = [ ] , K ) {
30
+ let count = new Array ( A . length ) . fill ( 0 ) ; // mảng cộng dồn, count[i] minh họa số phần tử bằng K trong đoạn từ 0 đến i
31
+ if ( A [ 0 ] === K ) count [ 0 ] = 1 ;
32
+ else count [ 0 ] = 0 ;
33
+ for ( let i = 1 ; i < A . length ; i ++ ) {
34
+ if ( A [ i ] === K ) count [ i ] = count [ i - 1 ] + 1 ;
35
+ else count [ i ] = count [ i - 1 ] ;
36
+ }
37
+
38
+ for ( let i = 0 ; i < Q . length ; i ++ ) {
39
+ let L = Q [ i ] [ 0 ] , R = Q [ i ] [ 1 ] ;
40
+ console . log ( count [ R ] - count [ L ] ) ;
41
+ }
42
+
43
+ return ;
44
+ }
45
+
46
+ return solution ( [ [ 0 , 3 ] , [ 1 , 2 ] , [ 3 , 9 ] ] , 2 ) ;
47
+ }
48
+
49
+ /**
50
+ * Given an array A has n elements
51
+ * There are #Q queries like (L_i, R_i, K_i) 1<= i <= Q
52
+ * Count
53
+ */
54
+
55
+ function main3 ( A ) {
56
+ if ( A . length === 0 ) return ;
57
+
58
+ function solution ( Q = [ ] ) {
59
+ let count = new Array ( A . length ) . fill ( 0 ) . map ( x => new Array ( 100 ) ) ; // count[i][K] đếm số lần xuất hiện của K trong đoạn từ 0 đến i
60
+ for ( let i = 0 ; i < A . length ; i ++ ) {
61
+ for ( let j = 0 ; j <= 2 ; j ++ ) {
62
+ if ( A [ i ] === j ) {
63
+ count [ i ] [ j ] = ( i >= 1 ) ? count [ i - 1 ] [ j ] + 1 : 1
64
+ } else {
65
+ count [ i ] [ j ] = ( i >= 1 ) ? count [ i - 1 ] [ j ] : 0
66
+ }
67
+ }
68
+ }
69
+
70
+ for ( let i = 0 ; i < Q . length ; i ++ ) {
71
+ let L = Q [ i ] [ 0 ] , R = Q [ i ] [ 1 ] , K = Q [ i ] [ 2 ] ;
72
+ console . log ( count [ R ] [ K ] - ( L >= 1 ? count [ L - 1 ] [ K ] : 0 ) ) ;
73
+ }
74
+
75
+ return ;
76
+ }
77
+
78
+ return solution ( [ [ 0 , 2 , 2 ] , [ 1 , 2 , 1 ] , [ 0 , 2 , 1 ] ] ) ;
79
+ }
80
+
81
+ console . log ( main3 ( [ 1 , 1 , 1 ] ) ) ;
82
+
83
+ // function rangeQueries (A = []) {
84
+ // if (A.length === 0) return;
85
+ // let count = new Array(3).fill(0).map(x => new Array(3));
86
+
87
+ // for (let i = 0; i < A.length; i++) {
88
+ // for (let j = 0; j < 3; j++) {
89
+ // if (j === A[i]) {
90
+ // count[i][j] = (i >= 1) ? count[i - 1][j] + 1 : 1;
91
+ // } else {
92
+ // count[i][j] = (i >= 1) ? count[i - 1][j] : 0;
93
+ // }
94
+ // }
95
+ // }
96
+ // return;
97
+ // }
98
+
99
+ // console.log(rangeQueries([2, 1, 1]));
0 commit comments