Skip to content

Conversation

@jhm9595
Copy link
Owner

@jhm9595 jhm9595 commented Sep 9, 2022

Time Complexity : O(N)


r2--;
c2++;
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think there's a better way to structure your code.

if (i % 2 == 0) {
	// moving up
	int r = i >= row ? row - 1 : i;
	int c = i < row ? 0 : i - row + 1;
	while(r < row && r >= 0 && c < col && c >= 0) {
		arr[idx++] = matrix[r][c];
		r--;
		c++;
	}
} else {
	// moving down
	int r = i < col ? 0 : i - col + 1;
	int c = i >= col ? col - 1 : i;
	while(r < row && r >= 0 && c < col && c >= 0) {
		arr[idx++] = matrix[r][c];
		r++;
		c--;
	}
}

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another option:

int r, c, deltaR, deltaC;
if (i % 2 == 0) {
	// moving up
	r = i >= row ? row - 1 : i;
	c = i < row ? 0 : i - row + 1;
	deltaR = -1;
	deltaC = 1;
} else {
	// moving down
	r = i < col ? 0 : i - col + 1;
	c = i >= col ? col - 1 : i;
	deltaR = 1;
	deltaC = -1;
}
while(r < row && r >= 0 && c < col && c >= 0) {
	arr[idx++] = matrix[r][c];
	r += deltaR;
	c += deltaC;
}

I personally like the first implementation better, but you can also consider the second one.

The reason why the first implementation is better is that we can declare "r" and "c" with "final". Using "final" as much as possible is a good practice in Java.

You can read: https://stackoverflow.com/questions/154314/when-should-one-use-final-for-method-parameters-and-local-variables

Copy link
Collaborator

@bigelephant29 bigelephant29 Sep 13, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But still, in the second implementation we remove more duplicate code. In this way it's easier for us to make the code into template and write unit tests on them.

@bigelephant29
Copy link
Collaborator

bigelephant29 commented Sep 13, 2022

Time complexity is not O(N). It's O(NM). Though at the end you put all the values into a single array, the time complexity is dependent upon the original 2D matrix.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants