tinycodinglm / cp /cp-10007.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 12)
3c88a0f verified
|
Raw History Blame Contribute Delete
1.82 kB
opencode trace
System You are an expert LeetCode problem solver. You solve problems efficiently with clean code.

You are an expert LeetCode problem solver. You solve problems efficiently with clean code.

User

Problem: Diagonal Traverse (Difficulty: Medium)
Tags: Array, Matrix, Simulation

Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order.

Example 1:
Input: mat = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,4,7,5,3,6,8,9]

Example 2:
Input: mat = [[1,2],[3,4]]
Output: [1,2,3,4]

Constraints:

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 10^4
  • 1 <= m * n <= 10^4
  • -10^5 <= mat[i][j] <= 10^5
Assistant

Time: O(m * n)

Space: O(1)

class Solution(object):
def findDiagonalOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if not matrix or not matrix[0]:
return []

markdown
result = []
    row, col, d = 0, 0, 0
    dirs = [(-1, 1), (1, -1)]

    for i in range(len(matrix) * len(matrix[0])):
        result.append(matrix[row][col])
        row += dirs[d][0]
        col += dirs[d][1]

        if row >= len(matrix):
            row = len(matrix) - 1
            col += 2
            d = 1 - d
        elif col >= len(matrix[0]):
            col = len(matrix[0]) - 1
            row += 2
            d = 1 - d
        elif row < 0:
            row = 0
            d = 1 - d
        elif col < 0:
            col = 0
            d = 1 - d

    return result