Given a list of lists of integers, nums
, return all elements of nums
in diagonal order as shown in the below images.
Example 1:
Input: nums = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,4,2,7,5,3,8,6,9]
Example 2:
Input: nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]] Output: [1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16]
Example 3:
Input: nums = [[1,2,3],[4],[5,6,7],[8],[9,10,11]] Output: [1,4,2,5,3,8,6,9,7,10,11]
Example 4:
Input: nums = [[1,2,3,4,5,6]] Output: [1,2,3,4,5,6]
Constraints:
1 <= nums.length <= 10^5
1 <= nums[i].length <= 10^5
1 <= nums[i][j] <= 10^9
- There at most
10^5
elements innums
.
Solution: Hashtable
Use diagonal index (i + j) as key.
Time complexity: O(n)
Space complexity: O(n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// Author: Huahua class Solution { public: vector<int> findDiagonalOrder(vector<vector<int>>& nums) { vector<vector<int>> m; for (int i = 0; i < nums.size(); ++i) for (int j = 0; j < nums[i].size(); ++j) { if (m.size() <= i + j) m.push_back({}); m[i + j].push_back(nums[i][j]); } vector<int> ans; for (const auto& d : m) ans.insert(end(ans), rbegin(d), rend(d)); return ans; } }; |
Python
1 2 3 4 5 6 7 8 9 |
# Author: Huahua class Solution: def findDiagonalOrder(self, nums): m = [] for i, row in enumerate(nums): for j, v in enumerate(row): if i + j >= len(m): m.append([]) m[i+j].append(v) return [v for d in m for v in reversed(d)] |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment