|
| 1 | +(* |
| 2 | +Given a 2D integer array matrix, return the transpose of matrix. |
| 3 | +
|
| 4 | +The transpose of a matrix is the matrix flipped over its main diagonal, |
| 5 | +switching the matrix's row and column indices. |
| 6 | +
|
| 7 | +Example 1: |
| 8 | +
|
| 9 | +Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] |
| 10 | +Output: [[1,4,7],[2,5,8],[3,6,9]] |
| 11 | +Example 2: |
| 12 | +
|
| 13 | +Input: matrix = [[1,2,3],[4,5,6]] |
| 14 | +Output: [ |
| 15 | + [1,4], |
| 16 | + [2,5], |
| 17 | + [3,6]] |
| 18 | + |
| 19 | +
|
| 20 | +Constraints: |
| 21 | +
|
| 22 | +m == matrix.length |
| 23 | +n == matrix[i].length |
| 24 | +1 <= m, n <= 1000 |
| 25 | +1 <= m * n <= 105 |
| 26 | +-109 <= matrix[i][j] <= 109 |
| 27 | +*) |
| 28 | +type matrix = int array array |
| 29 | +[@@deriving show] |
| 30 | + |
| 31 | +(** |
| 32 | +time O(n * m) |
| 33 | +space O(n * m) |
| 34 | +*) |
| 35 | +let transpose (matrix : matrix) : matrix = |
| 36 | + let rows = Array.length matrix in |
| 37 | + |
| 38 | + if rows = 0 then [||] |
| 39 | + else |
| 40 | + let columns= Array.length matrix.(0) in |
| 41 | + |
| 42 | + let transposed = Array.init columns (fun _ -> Array.make rows 0) in |
| 43 | + |
| 44 | + matrix |
| 45 | + |> Array.iteri (fun i row -> |
| 46 | + row |> Array.iteri (fun j _ -> |
| 47 | + transposed.(j).(i) <- matrix.(i).(j);)); |
| 48 | + |
| 49 | + transposed |
| 50 | + |
| 51 | +let%test_unit "transpose: examples" = |
| 52 | + [ |
| 53 | + ([||], [||]); |
| 54 | + ([|[|1;2;3|];[|4;5;6|];[|7;8;9|]|],[|[|1;4;7|];[|2;5;8|];[|3;6;9|]|]); |
| 55 | + ([|[|1;2;3|];[|4;5;6|]|], [|[|1;4|];[|2;5|];[|3;6|]|]) |
| 56 | + ] |> |
| 57 | + List.iter (fun (matrix, expected) -> |
| 58 | + assert (expected = transpose matrix) |
| 59 | + ) |
0 commit comments