【題解】LeetCode 1424. Diagonal Traverse II

【題目敘述】https://leetcode.com/problems/diagonal-traverse-ii/

bool cmp(pair<int, int>x, pair<int, int>y){
        if (x.first+x.second != y.first+y.second){
            return x.first+x.second < y.first+y.second;
        }
        return x.first > y.first;
}
class Solution {
public:
    vector<int> findDiagonalOrder(vector<vector<int>>& nums) {
        vector <int> ans;
        vector <pair<int, int> > idx;
        int l = nums.size();
        for (int i = 0; i < l; i++){
            for (int j = 0; j < nums[i].size(); j++){
                idx.push_back({i, j});
            }
        }
        sort(idx.begin(), idx.end(), cmp);
        for (int i = 0; i < idx.size(); i++){
            ans.push_back(nums[idx[i].first][idx[i].second]);
        }
        return ans;
    }
};
分享本文 Share with friends