File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change @@ -263,3 +263,52 @@ if __name__ == "__main__":
263263 main()
264264
265265```
266+
267+ ### JavaScript
268+
269+ ``` JavaScript
270+
271+ function prefixSum () {
272+ const readline = require (' readline' );
273+
274+ const rl = readline .createInterface ({
275+ input: process .stdin ,
276+ output: process .stdout
277+ });
278+
279+ let inputLines = [];
280+ rl .on (' line' , (line ) => {
281+ inputLines .push (line .trim ());
282+ });
283+
284+ rl .on (' close' , () => {
285+ // 读取项数 n
286+ const n = parseInt (inputLines[0 ]);
287+
288+ // 使用前缀和,复杂度控制在 O(1)
289+ let sum = new Array (n);
290+ sum[0 ] = parseInt (inputLines[1 ]);
291+
292+ // 计算前缀和数组
293+ for (let i = 1 ; i < n; i++ ) {
294+ let value = parseInt (inputLines[i + 1 ]);
295+ sum[i] = sum[i - 1 ] + value;
296+ }
297+
298+ // 处理区间和查询
299+ for (let i = n + 1 ; i < inputLines .length ; i++ ) {
300+ let [left, right] = inputLines[i].split (' ' ).map (Number );
301+
302+ if (left === 0 ) {
303+ console .log (sum[right]);
304+ } else {
305+ console .log (sum[right] - sum[left - 1 ]);
306+ }
307+ }
308+ });
309+ }
310+
311+
312+ ```
313+
314+
You can’t perform that action at this time.
0 commit comments