jason89521 / leetcode_note

0 stars 0 forks source link

48. Rotate Image #10

Open jason89521 opened 3 months ago

jason89521 commented 3 months ago

Practice Dates

Description

Link: https://leetcode.com/problems/rotate-image/description/

Solution

Swap the top left with the top right, then swap the top left with the right bottom, and finally swap the top left with the left bottom. Continue this process until all elements in the matrix are swapped.

fn swap(matrix: &mut Vec<Vec<i32>>, pos_1: (usize, usize), pos_2: (usize, usize)) {
    let temp = matrix[pos_1.0][pos_1.1];
    matrix[pos_1.0][pos_1.1] = matrix[pos_2.0][pos_2.1];
    matrix[pos_2.0][pos_2.1] = temp;
}

impl Solution {
    pub fn rotate(matrix: &mut Vec<Vec<i32>>) {
        let n = matrix.len();
        for i in 0..n/2 {
            let length = n - 2 * i;
            let last = i + length - 1;
            for j in 0..length-1 {
                if i == 1 {
                    println!("i: {}, j: {}, length: {}", i, j, length);
                }
                let left_corner = (i, i+j);
                swap(matrix, left_corner, (i+j, last));
                swap(matrix, left_corner, (last, last-j));
                swap(matrix, left_corner, (last-j, i));
            }
        }

    }
}

Performance

Time complexity:

jason89521 commented 3 months ago

There is another approach: transpose the matrix first, then reverse all the rows in the matrix.