Enumerate grid points on 2D plane with descending order of (x * y)

前端 未结 8 1273
轻奢々
轻奢々 2021-02-09 11:55

Given N > 0 and M > 0, I want to enumerate all (x, y) pairs such that 1 <= x <= N and 1 <= y <= M in descending order of (x * y). An

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-09 12:11

    Because you mention that most of the time you need the first few terms of the sequence; after generating them all you don't need to sort them all to find these first few terms. You can use a Max Heap depending on number of terms that you want, say k. So if a heap is of size k (<< N && << M) then you can have largest k terms after nlogk which is better than nlogn for sorting.

    Here n = N*M

提交回复
热议问题