LeetCode 2326. Spiral Matrix IV
原题链接在这里:https://leetcode.com/problems/spiral-matrix-iv/description/
题目:
You are given two integers m
and n
, which represent the dimensions of a matrix.
You are also given the head
of a linked list of integers.
Generate an m x n
matrix that contains the integers in the linked list presented in spiral order (clockwise), starting from the top-left of the matrix. If there are remaining empty spaces, fill them with -1
.
Return the generated matrix.
Example 1:
Input: m = 3, n = 5, head = [3,0,2,6,8,1,7,9,4,2,5,5,0] Output: [[3,0,2,6,8],[5,0,-1,-1,1],[5,2,4,9,7]] Explanation: The diagram above shows how the values are printed in the matrix. Note that the remaining spaces in the matrix are filled with -1.
Example 2:
Input: m = 1, n = 4, head = [0,1,2] Output: [[0,1,2,-1]] Explanation: The diagram above shows how the values are printed from left to right in the matrix. The last space in the matrix is set to -1.
Constraints:
1 <= m, n <= 105
1 <= m * n <= 105
- The number of nodes in the list is in the range
[1, m * n]
. 0 <= Node.val <= 1000
题解:
It is the same spriral traversal.
The while condition is r1 <= r2 && c1 <= c2.
For the last row or last column, we only need to traverse to the right or down, no need to traverse to the left or up.
Check r1 < r2 and c1 < c2 to see if there is only one row or column left.
Time Complexity: O(m * n).
Space: O(1). regardless res.
AC Java:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode() {} 7 * ListNode(int val) { this.val = val; } 8 * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 * } 10 */ 11 class Solution { 12 public int[][] spiralMatrix(int m, int n, ListNode head) { 13 int [][] res = new int[m][n]; 14 int r1 = 0; 15 int r2 = m - 1; 16 int c1 = 0; 17 int c2 = n - 1; 18 int ind = 0; 19 while(r1 <= r2 && c1 <= c2){ 20 for(int c = c1; c <= c2; c++){ 21 if(head == null){ 22 res[r1][c] = -1; 23 }else{ 24 res[r1][c] = head.val; 25 head = head.next; 26 } 27 } 28 29 for(int r = r1 + 1; r <= r2; r++){ 30 if(head == null){ 31 res[r][c2] = -1; 32 }else{ 33 res[r][c2] = head.val; 34 head = head.next; 35 } 36 } 37 38 if(r1 < r2 && c1 < c2){ 39 for(int c = c2 - 1; c >= c1; c--){ 40 if(head == null){ 41 res[r2][c] = -1; 42 }else{ 43 res[r2][c] = head.val; 44 head = head.next; 45 } 46 } 47 48 for(int r = r2 - 1; r > r1; r--){ 49 if(head == null){ 50 res[r][c1] = -1; 51 }else{ 52 res[r][c1] = head.val; 53 head = head.next; 54 } 55 } 56 } 57 58 r1++; 59 r2--; 60 c1++; 61 c2--; 62 } 63 64 return res; 65 } 66 }