Remember Amazon's OA topic, as if given a matrix, let the matrix of each element to the right shift a position. The problem was not well thought out before. Today I just brushed the rotate matrix, so just a piece of thinking.
The idea is similar to the Leetcode Spiral Matrix:
The
- assumes that the matrix is a phalanx
- setting top, left, bot, right four boundary variables, and then a circle of shift from the outer ring to the most inner ring.
- sets a count when the count < total elements in matrix shift
- is recorded at the beginning of each lap Matrix[top][left], and then starts the shift ol>
- from top to bot
- from left to right
- from bot to top
- right to left
- results from the last edge try to update the new Matrix[top][left], this time the top for the old, and left has been updated once, we want to be divided into two situations consider
- count! = totalElements-1, when we want to:
- matrix[top][left] Update to TMP
- count++
- top++
- go to the next lap /li>
- otherwise count = = TotalElements-1, also divided into two cases
- totalelements is odd, we do not change Matrix[top][left]
- totalelements is even, we still need to update matrix[top][left] = tmp
- then count++ end Loop Returns the result
- If a given matrix is not a square, then we have to add more judgments, such as when the last row or last column is not updated. The last line or the last column can be bot-top or right-left to find out the
Time Complexity-o (MN), Space complexity-o (1), in place.
Public classSolution { Public voidRotatematrixbyone (int[] matrix) { if(Matrix = =NULL|| Matrix[0] = =NULL) { return; } intm =matrix.length; intn = matrix[0].length; intleft = 0, top = 0, right = n-1, bot = m-1; intCount = 0; inttotalelements = m *N; while(Count <totalelements) { intTMP =Matrix[top][left]; if(Count <totalelements) { for(inti = top; i < bot; i++) {Matrix[i][left]= Matrix[i + 1][left]; Count++; } Left++; } if(Count <totalelements) { for(inti = left-1; I < right; i++) {Matrix[bot][i]= Matrix[bot][i + 1]; Count++; } bot--; } if(Count <totalelements) { for(inti = bot + 1; i > top; i--) {Matrix[i][right]= Matrix[i-1][right]; Count++; } Right--; } if(Count <totalelements) { for(inti = right + 1; i > left; i--) {Matrix[top][i]= Matrix[top][i-1]; Count++; } if(Count! = totalElements-1) {Matrix[top][left]=tmp; } Else if(totalelements% 2 = = 0) {Matrix[top][left]=tmp; } Count++; Top++; } } }}
Rotate Matrix by one