1424. Diagonal Traverse II

  • 쒌츑 상단 μ½”λ„ˆ λΆ€ν„° μ‹œμž‘ν•˜μ—¬ μœ„ & 였λ₯Έμͺ½ λ°©ν–₯ λŒ€κ°μ„ μœΌλ‘œ λͺ¨λ“  숫자λ₯Ό μ½μ–΄μ„œ λŒλ €μ£Όμ–΄μ•Ό ν•˜λŠ” λ¬Έμ œμ΄λ‹€.
  • 문제λ₯Ό μžˆλŠ” κ·ΈλŒ€λ‘œ ν•΄μ„ν•˜μ—¬ κ΅¬ν˜„ν•  경우 μ‹œκ°„ λ³΅μž‘λ„κ°€ 에 κ·Όμ ‘ν•  수 있으며 μ‹œκ°„ 초과둜 μ‹€νŒ¨ν•œλ‹€.
    • 행렬에 ν¬ν•¨λœ 전체 숫자의 κ°œμˆ˜λŠ” 개 μ΄μ§€λ§Œ row, column의 μ΅œλŒ€ 길이도 각각 κ°€ 될 수 μžˆμœΌλ―€λ‘œ loopλ₯Ό 잘λͺ» μž‘μ„±ν•˜λ©΄ 만큼 μ‹œλ„ν•˜κ²Œ 될 수 μžˆλ‹€.
    • 첫번째 힌트(같은 λŒ€κ°μ„ μ— μ†ν•œ 숫자의 row, column index 합은 κ°™λ‹€)λ₯Ό 보고 ν’€μ—ˆλ‹€.
  • ν–‰λ ¬μ˜ 각 숫자λ₯Ό μ ‘κ·Όν•˜λŠ” index pair의 λͺ©λ‘μ„ λ§Œλ“€κ³  이것을 μ›ν•˜λŠ” μˆœμ„œλ‘œ μ •λ ¬ν•˜μ—¬ 문제λ₯Ό ν•΄κ²°ν•  수 μžˆλ‹€.
    • λ¨Όμ € ν–‰λ ¬μ˜ 각 μ›μ†Œλ₯Ό μ ‘κ·Όν•  수 μžˆλŠ” index pair의 λͺ©λ‘μ„ λ§Œλ“ λ‹€.
    • index pairλ₯Ό μ •λ ¬ν•œλ‹€.
      • 각 λŒ€κ°μ„ μ— ν¬ν•¨λœ μ›μ†Œμ˜ row, column index의 합이 λ™μΌν•˜κ³  합이 μž‘μ€ λŒ€κ°μ„  λΆ€ν„° μ ‘κ·Όν•΄μ•Ό ν•œλ‹€.
      • λ”°λΌμ„œ row, column index의 합이 λ‹€λ₯Έ 경우 μž‘μ€ μˆœμ„œλŒ€λ‘œ μ •λ ¬ν•œλ‹€.
      • λ§Œμ•½ row, column index의 합이 κ°™λ‹€λ©΄ row indexκ°€ 큰 것이 λ¨Όμ € μ˜€λ„λ‘ μ •λ ¬ν•œλ‹€.
    • μ •λ ¬λœ index pair λͺ©λ‘μ„ μ΄μš©ν•˜μ—¬ ν–‰λ ¬μ˜ 각 숫자λ₯Ό μ ‘κ·Όν•˜μ—¬ λŒλ €μ€€λ‹€.
class Solution { public: vector<int> findDiagonalOrder(vector<vector<int>>& nums) { vector<pair<int, int>> indices; for (int i = 0; i < nums.size(); ++i) { int n = nums[i].size(); for (int j = 0; j < n; ++j) { indices.emplace_back(i, j); } } auto compare = [](pair<int, int>& a, pair<int, int>& b) { int aSum = a.first + a.second; int bSum = b.first + b.second; return aSum != bSum? aSum < bSum : a.first > b.first; }; sort(indices.begin(), indices.end(), compare); vector<int> result; result.reserve(indices.size()); for (auto& i : indices) { result.push_back(nums[i.first][i.second]); } return result; } };