배열을 두 배로 배열 한 다음 n을 가장 낮게 (0이 아닌) 찾습니다 (배열 을이라고 부름). 루프를 여러 번 반복해야하므로 실행 속도가 중요합니다. , 배열에서 가장 낮은 n을 얻는 가장 빠른 방법
const int numLowestSamples = 10;
double[] samples;
double[] lowestSamples = new double[numLowestSamples];
for (int count = 0; count < iterations; count++) // iterations typically around 2600000
{
samples = whatever;
Array.Sort(samples);
lowestSamples = samples.SkipWhile(x => x == 0).Take(numLowestSamples).ToArray();
}
따라서 I 다른 시도 : I 먼저 배열을 정렬 한 후 처음 10 개 개의 값 (0이되지 않는)에 Array.sort 빠른 것으로 알려져 있지만, 그러나, 병목되었다 복용 시도 첫 번째 n 값을 먼저 읽고 값을 정렬 한 다음 다른 모든 값을
샘플으로 반복하여 값이 정렬 된 마지막 값인
lowestSamples 배열보다 작 으면 검사합니다. 값이 낮 으면 배열의 값으로 바꾸고 배열을 다시 정렬합니다. 이 약 5 배 빠른 것으로 밝혀졌다 :
const int numLowestSamples = 10;
double[] samples;
List<double> lowestSamples = new List<double>();
for (int count = 0; count < iterations; count++) // iterations typically around 2600000
{
samples = whatever;
lowestSamples.Clear();
// Read first n values
int i = 0;
do
{
if (samples[i] > 0)
lowestSamples.Add(samples[i]);
i++;
} while (lowestSamples.Count < numLowestSamples)
// Sort the array
lowestSamples.Sort();
for (int j = numLowestSamples; j < samples.Count; j++) // samples.Count is typically 3600
{
// if value is larger than 0, but lower than last/highest value in lowestSamples
// write value to array (replacing the last/highest value), then sort array so
// last value in array still is the highest
if (samples[j] > 0 && samples[j] < lowestSamples[numLowestSamples - 1])
{
lowestSamples[numLowestSamples - 1] = samples[j];
lowestSamples.Sort();
}
}
}
이 상대적으로 빠른 작동하지만, 내가 더 빠르고 더 나은 해결책을 마련하기 위해 사람을 도전하고 싶었다.
min-heap을 유지하는 것이 좋은 해결책인지 궁금합니다. – ChaosPandion
ChaosPandion : 5 초 만에 나를 이길;) – robbrit
이것이 일회 불리는 것이라면 여분의 작업/복잡성 (코드 유지 관리 측면에서 볼 때)이 필요한 성능입니다. – Jake1164