2610 转换二维数组

·   ·   ·   ·

  ·   ·


题目链接

2610. 转换二维数组

分析

使用一个哈希表记录每个数字出现的次数,然后放到对应行的数组里即可

由于题目保证数据在 $1-n$,所以可以使用数组存储加速运算

代码实现

class Solution {
public:
    vector<vector<int>> findMatrix(vector<int>& nums) {
        int n = nums.size();
        vector<int> cnt(n + 1, 0);
        vector<vector<int>> ans;

        for(int i : nums) {
            if(cnt[i] == ans.size()) {
                ans.emplace_back();
            }
            ans[cnt[i]++].emplace_back(i);
        }

        return ans;
    }
};

复杂度分析

  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$