|
| 1 | +/** |
| 2 | + * [1424] Diagonal Traverse II |
| 3 | + * |
| 4 | + * Given a list of lists of integers, nums, return all elements of nums in diagonal order as shown in the below images. |
| 5 | + * |
| 6 | + * Example 1: |
| 7 | + * <img alt="" src="https://assets.leetcode.com/uploads/2020/04/08/sample_1_1784.png" style="width: 158px; height: 143px;" /> |
| 8 | + * |
| 9 | + * Input: nums = [[1,2,3],[4,5,6],[7,8,9]] |
| 10 | + * Output: [1,4,2,7,5,3,8,6,9] |
| 11 | + * |
| 12 | + * Example 2: |
| 13 | + * <img alt="" src="https://assets.leetcode.com/uploads/2020/04/08/sample_2_1784.png" style="width: 230px; height: 177px;" /> |
| 14 | + * |
| 15 | + * Input: nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]] |
| 16 | + * Output: [1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16] |
| 17 | + * |
| 18 | + * Example 3: |
| 19 | + * |
| 20 | + * Input: nums = [[1,2,3],[4],[5,6,7],[8],[9,10,11]] |
| 21 | + * Output: [1,4,2,5,3,8,6,9,7,10,11] |
| 22 | + * |
| 23 | + * Example 4: |
| 24 | + * |
| 25 | + * Input: nums = [[1,2,3,4,5,6]] |
| 26 | + * Output: [1,2,3,4,5,6] |
| 27 | + * |
| 28 | + * |
| 29 | + * Constraints: |
| 30 | + * |
| 31 | + * 1 <= nums.length <= 10^5 |
| 32 | + * 1 <= nums[i].length <= 10^5 |
| 33 | + * 1 <= nums[i][j] <= 10^9 |
| 34 | + * There at most 10^5 elements in nums. |
| 35 | + * |
| 36 | + */ |
| 37 | +pub struct Solution {} |
| 38 | + |
| 39 | +// problem: https://leetcode.com/problems/diagonal-traverse-ii/ |
| 40 | +// discuss: https://leetcode.com/problems/diagonal-traverse-ii/discuss/?currentPage=1&orderBy=most_votes&query= |
| 41 | + |
| 42 | +// submission codes start here |
| 43 | + |
| 44 | +impl Solution { |
| 45 | + pub fn find_diagonal_order(nums: Vec<Vec<i32>>) -> Vec<i32> { |
| 46 | + let mut start_positions : Vec<(i32,i32)> = vec![]; |
| 47 | + let row_count : usize = nums.len(); |
| 48 | + let col_count : usize = nums[0].len(); |
| 49 | + for i in 0..row_count { |
| 50 | + start_positions.push((i as i32, 0 as i32)); |
| 51 | + } |
| 52 | + for j in 1..col_count { |
| 53 | + start_positions.push((row_count as i32 - 1, j as i32)); |
| 54 | + } |
| 55 | + |
| 56 | + let mut result : Vec<i32> = vec![]; |
| 57 | + for start_pos in start_positions.iter() { |
| 58 | + let mut i = start_pos.0; |
| 59 | + let mut j = start_pos.1; |
| 60 | + while 0 <= i && i < row_count as i32 && 0 <=j && j < col_count as i32 { |
| 61 | + result.push(nums[i as usize][j as usize]); |
| 62 | + i-=1; |
| 63 | + j+=1; |
| 64 | + } |
| 65 | + } |
| 66 | + result |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +// submission codes end |
| 71 | + |
| 72 | +#[cfg(test)] |
| 73 | +mod tests { |
| 74 | + use super::*; |
| 75 | + |
| 76 | + #[test] |
| 77 | + fn test_1424() { |
| 78 | + assert_eq!(Solution::find_diagonal_order(vec![vec![1,2,3],vec![4,5,6],vec![7,8,9]]), vec![1,4,2,7,5,3,8,6,9]); |
| 79 | + } |
| 80 | +} |
0 commit comments