-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Closed
Description
Time complexity of this program is fine O(n*m), but space complexity can be O(1).
Here is my code,
import java.util.ArrayList;
import java.util.List;
class Solution
{
public List<Integer> spiralOrder(int[][] A)
{
if ((A == null) || (A.length == 0) || (A[0].length == 0))
{
return (new ArrayList <Integer> ());
}
int lr = 0, ur = A.length, lc = 0, uc = A[0].length;
List <Integer> arr = new ArrayList <Integer> ();
int count = 0, t = 0, x = 0, y = 0;
int offset [] = {0, 1};
while (count < (A.length * A[0].length))
{
if (((y + offset[1]) == uc) || ((x + offset[0]) == ur) || ((y + offset[1]) < lc) || ((x + offset[0]) < lr))
{
if (((y + offset[1]) == uc))
{
lr += 1;
}
else if (((x + offset[0]) == ur))
{
uc -= 1;
}
else if (((y + offset[1]) < lc))
{
ur -= 1;
}
else if (((x + offset[0]) < lr))
{
lc += 1;
}
t = offset[0];
offset[0] = offset[1];
offset[1] = -t;
}
arr.add(A[x][y]);
x += offset[0];
y += offset[1];
count += 1;
}
return (arr);
}
}
Let me know what you think sir, 😉 😄 .
If you don't consider the array to be returned and just print the values as they are, space complexity will be O(1).
Metadata
Metadata
Assignees
Labels
No labels