码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode] Rotate Image

时间:2015-09-04 16:55:05      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

描述:

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Follow up:
Could you do this in-place?

分析:

先将矩阵转置,然后翻转即可,也可以按公式进行计算

code:

    /*
    rotate image
    时间复杂度 O(n^2),空间复杂度 O(1)
    */
    void rotate(vector<vector<int>> &matrix)
    {
        int n = matrix.size();
        //转置矩阵
        for (size_t i = 0; i < n; i++)
        {
            for (size_t j = 0; j < i; j++)
            {
                swap(matrix[i][j], matrix[j][i]);
            }
        }
        //左右翻转
        for (size_t i = 0; i < n; i++)
        {
            for (size_t j = 0; j < n/2; j++)
            {
                swap(matrix[i][j], matrix[i][n-1-j]);
            }
        }
    }

[leetcode] Rotate Image

标签:

原文地址:http://www.cnblogs.com/panweishadow/p/4781802.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!