LeetCode每日一题(1632. Rank Transform of a Matrix)

给定一个矩阵,返回一个新矩阵,其中新矩阵的每个元素是其原始位置元素的排名。排名根据特定规则计算:同一行或列中,较小的元素排名更低。通过比较元素并维护行和列的最大值来确定排名。

Given an m x n matrix, return a new matrix answer where answer[row][col] is the rank of matrix[row][col].

The rank is an integer that represents how large an element is compared to other elements. It is calculated using the following rules:

The rank is an integer starting from 1.
If two elements p and q are in the same row or column, then:
If p < q then rank§ < rank(q)
If p == q then rank§ == rank(q)
If p > q then rank§ > rank(q)
The rank should be as small as possible.
The test cases are generated so that answer is unique under the given rules.

Example 1:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GZDeCS8y-1677080795564)(null)]

Input: matrix = [[1,2],[3,4]]
Output: [[1,2],[2,3]]

Explanation:
The rank of matrix[0][0] is 1 because it is the smallest integer in its row and column.
The rank of matrix[0][1] is 2 because matrix[0][1] > matrix[0][0] and matrix[0][0] is rank 1.
The rank of matrix[1][0] is 2 because matrix[1][0] > matrix[0][0] and matrix[0][0] is rank 1.
The rank of matrix[1][1] is 3 because matrix[1][1] > matrix[0][1], matrix[1][1] > matrix[1][0], and both matrix[0][1] and matrix[1][0] are rank 2.

Example 2:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CdFe2Wnr-1677080797518)(null)]

Input: matrix = [[7,7],[7,7]]
Output: [[1,1],[1,1]]

Example 3:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JORDYrOV-1677080795386)(null)]

Input: matrix = [[20,-21,14],[-19,4,19],[22,-47,24],[-19,4,19]]
Output: [[4,2,3],[1,3,4],[5,1,6],[1,3,4]]

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 500
  • -109 <= matrix[row][col] <= 109

将 value 相同的 cells 收集到一起并排序, 然后遍历该数组,我们就可以从小到大的处理这些 cells, 维护每行和每列的最大值, 因为是从小到大的进行处理, 所以我们只需要找 cell 所在行和所在列当前的最大值即可, 最大值+1 就是该 cell 的 rank, 但是如果相同行或者相同列上有 value 相同的 cells, 这些同行或者同列的 cells 实际是相互联通的, 我们要将它们视作一个整体来查找这些 cells 所在行和列的最大值, 这里我们用 union-find 的方法来将这些 value 相同的 cells 分成独立的 components, 然后每个 component 查找一个最大值赋给 component 中的 cells



use std::collections::HashMap;

impl Solution {
    fn find(parents: &mut Vec<usize>, i: usize) -> usize {
        if parents[i] == i {
            return i;
        }
        let p = Solution::find(parents, parents[i]);
        parents[i] = p;
        return p;
    }

    pub fn matrix_rank_transform(matrix: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
        let positions: HashMap<i32, Vec<(usize, usize)>> =
            matrix
                .iter()
                .enumerate()
                .fold(HashMap::new(), |mut m, (r, l)| {
                    l.into_iter().enumerate().for_each(|(c, &v)| {
                        m.entry(v).or_insert(Vec::new()).push((r, c));
                    });
                    m
                });
        let mut positions: Vec<(i32, Vec<(usize, usize)>)> =
            positions.into_iter().map(|(k, v)| (k, v)).collect();
        positions.sort();
        let mut row_maxes = vec![0; matrix.len()];
        let mut col_maxes = vec![0; matrix[0].len()];
        let mut ans = vec![vec![0; matrix[0].len()]; matrix.len()];
        for (_, ps) in positions {
            let mut same_rows = HashMap::new();
            let mut same_cols = HashMap::new();
            let mut parents: Vec<usize> = Vec::new();
            for i in 0..ps.len() {
                same_rows.entry(ps[i].0).or_insert(Vec::new()).push(i);
                same_cols.entry(ps[i].1).or_insert(Vec::new()).push(i);
                parents.push(i);
            }
            for i in 0..ps.len() {
                for &ri in same_rows.get(&ps[i].0).unwrap() {
                    if ri >= i {
                        continue;
                    }
                    let p = Solution::find(&mut parents, ri);
                    parents[p] = i;
                }
                for &ci in same_cols.get(&ps[i].1).unwrap() {
                    if ci >= i {
                        continue;
                    }
                    let p = Solution::find(&mut parents, ci);
                    parents[p] = i;
                }
            }
            let mut m = HashMap::new();
            for i in 0..ps.len() {
                let p = Solution::find(&mut parents, i);
                m.entry(p).or_insert(Vec::new()).push(ps[i]);
            }
            for group in m.values() {
                let mut max = 0;
                for &(r, c) in group {
                    max = max.max(row_maxes[r]);
                    max = max.max(col_maxes[c]);
                }
                for &(r, c) in group {
                    row_maxes[r] = max + 1;
                    col_maxes[c] = max + 1;
                    ans[r][c] = max + 1;
                }
            }
        }
        ans
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值