What is the fastest way to sort these n ^ 2 numbers?

Given the number "n", I want to return a sorted array of n ^ 2 numbers containing all the values ​​k1 * k2, where k1 and k2 can vary from 1 to n.

For example, for n = 2, it would return: {1,2,2,4}. (the number is basically 1 * 1.1 * 2.2 * 1.2 * 2).

and for n = 3 it will return: {1,2,2,3,3,4,6,6,9}.

(numbers: 1 * 1, 2 * 1, 1 * 2, 2 * 2, 3 * 1, 1 * 3, 3 * 2, 2 * 3, 3 * 3)

I tried using the sort function from the C ++ standard library, but I was wondering if it could be optimized.

+4
source share
2 answers

, -, n^2, n^2, , n . , :

  • counts[] n^2 .
  • values[] counts[values[i]-1]++.
  • values, counts, i+1 values, counts[i] .

. O(n^2), .

+4
vector<int> count(n*n+1);
for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= n; ++j)
        ++count[i*j];
for (int i = 1; i <= n*n; ++i)
    for (int j = 0; j < count[i]; ++j)
        cout << i << " ";

, , O (n * n), cmaster.

+3

Source: https://habr.com/ru/post/1672999/


All Articles