问题
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