leetcode-方阵原地转置

最近刷题,虽然刷题的效率还是比较低,但是最近的测试耗时居然超过了99%的用户,还是比较开心的,如何才能让思路更快呢?如何才能不依赖IDE调试就直接写出合适的算法呢?这是应该多思考的问题。
不讲多余的话了:
给定N*N的方阵,要求不另外开辟内存,直接在原矩阵上对方阵转置。
代码如下:

void rotate(std::vector<std::vector<int>>& matrix) {
    int n = matrix.size();
    int to_row = 0, from_row = 0;
    int to_col = 0, from_col = 0;
    int temp_i = 0;
    for(int i = 0; i < n - 1; ++i)
    {
        for(int j = i; j < n - 1 -i; ++j)
        {
            to_row = i;
            to_col = j;
            temp_i = matrix[to_row][to_col];
            for(int k =0; k< 3; ++k)
            {
                from_row = n - to_col -1 ;
                from_col = to_row;
                matrix[to_row][to_col] = matrix[from_row][from_col];
                to_row = from_row;
                to_col = from_col;
            }
            matrix[to_row][to_col] = temp_i;
        }
    }

}

猜你喜欢

转载自blog.csdn.net/mixiaoxinmiss/article/details/81042886
今日推荐