D
D
dmitriyivvvv2019-03-25 22:59:38
JavaScript
dmitriyivvvv, 2019-03-25 22:59:38

Yandex Contest how to get rid of Memory Limit/Time Limit error?

There is the following task: yandex contest
There are 2 solutions:

//Решение 1:
const fs = require('fs');
const readline = require('readline');

const rl = readline.createInterface({
  input: fs.createReadStream('input.txt'),
  terminal: false
});

let prev;

rl.once('line', () => {
  rl.on('line', line => {
    if (line != prev) fs.appendFileSync('output.txt', `${prev ? '\n' : ''}${prev = line}`);
  });
});

//Решение 2:
const fs = require('fs');
const readline = require('readline');

const rl = readline.createInterface({
  input: fs.createReadStream('input.txt'),
  terminal: false
});

let prev;

rl.once('line', () => {
  rl.on('line', line => {
    if (line != prev) process.stdout.write(`${prev ? '\n' : ''}${prev = line}`);
  });
});

The problem of the 1st solution is the time limit (1s) is exceeded, and the second is the memory limit (20 MB). How can this code be optimized?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
longclaps, 2019-03-25
@dmitriyivvvv

Pseudocode

открыл файл
a = прочитал одно число
пока файл не кончился
    b = прочитал одно число
    если a < b
        вывел a
        a = b
вывел a

K
krong, 2021-10-24
@krong

the solution actually boils down to just removing duplicates from the input array
using System;
using System.Linq;
namespace Test {
class Program {
static void Main() {
int n = Convert.ToInt32(Console.ReadLine());
int i = 0;
int[]mass = new int[n];
while (n > 0) {
mass[i] = Convert.ToInt32(Console.ReadLine());
n--; i++;
}
mass = mass.Distinct().ToArray();
GC.SuppressFinalize(n); GC.SuppressFinalize(i);
GC.Collect();
foreach (var item in mass) {
Console WriteLine(item);
}
}
}
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question