Distance between coordinates in Big-oh of M time

岁酱吖の 提交于 2019-12-12 03:34:02

问题


I have an array of coordinates, i.e each index contains (x,y) coordinates. I want to figure out that if any of the coordinates are in single row or column. The challenge is to do in a single loop where M is the length of the array. I have been trying hard but cant seem to do it without using two loops. Just need help with the algorithm.

Edit: Basically the problem is that I have M pieces on an N by N board. Each piece can move any vertically and horizontally by any number. Just want to figure out that if any piece can attack any other piece.


回答1:


This is element distinctness/uniqueness problem that has complexity O(MLogm) in common case (i.e. sorting).

If there are no memory limitations, you can use hash tables for Y and X coordinates, in this case single run through array solves the problem

Edit: For limited board it is simpler to use boolean array length N for horizontals and verticals. Time complexity O(M), memory consumption O(N)

for every rook:
    if Horiz[rook.Y] then
        two rooks share horizontal
    if Vert[rook.X] then
        two rooks share the same vertical
    Horiz[rook.Y] = True
    Vert[rook.X] = True


来源:https://stackoverflow.com/questions/41994416/distance-between-coordinates-in-big-oh-of-m-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!