Lecode刷题笔记-1-15

题目链接

06.01.01 练习题目(第 01 天)​​​​​​

笔记:

一. 螺旋矩阵

.

遍历方法:

1.走一行删一行,走一列删一列

int rows=m matrix.size();int cols= matrix[0].size();
int num=0;

int left=0;int up=0;int down=rows;int right=cols;

while(1){

    for(int i=left;i<right;i++) ans[num++]= matrix[up][i];
    if(++up<down-1)break;

    for(int i=up;i<down;i++) ans[num++]= matrix[right][i];
    if(--right>left)break;

    for(int i=right;i>=left;i--) matrix[down][i]=num++;
    if(--down<up) break;

     for(int i=down;i>=up;i--) matrix[i][left]=num++;
     if(++left>right)break;       
}

 2.模拟

directions[4][2]
class Solution {
private:
    static constexpr int directions[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    //{0,1} 向右走,{1,0},向下走,{0,-1}向左走,{-1,0}向上走
public:
    vector<vector<int>> generateMatrix(int n) {

        vector<vector<int>> matrix(n, vector<int>(n));
        if (n == 0)
            return matrix;

        int num = 1;
        vector<vector<bool>> visited(n, vector<bool>(n));
        int row = 0;int col = 0; //遍历使用
        int rows = n; int cols = n;
        int index = 0;

        while (num <= n * n) {
            visited[row][col] = true;
           //对 matrix[row][col]执行操作 

            int nextrow = row + directions[index][0];
            int nextcol = col + directions[index][1];
            if (nextrow >= n || nextcol >= n || nextrow < 0 || nextcol < 0 ||
                visited[nextrow][nextcol])
                index = (index + 1) % 4;
            row = row + directions[index][0];
            col = col + directions[index][1];
        }
        return matrix;
    }
};

 二、旋转图像

swap(ans[i][j],ans[n][m]);

 矩阵的旋转,可以考虑对角线,或者找规律。

行互换时,只需要换半个行,列全换;(for)

        for(int i=0;i<n/2;i++)
            for(int j=0;j<n;j++)
               swap(matrix[i][j], matrix[n - i - 1][j]);

        

主对角线互换时,换斜着的一半

        for(int i=0;i<n;i++){
            for(int j=0;j<i;j++)
                swap(matrix[i][j],matrix[j][i] );

 三、数组中的第K个最大元素

1.方法一:C++sort排序: 

动态数组:

sort(ans.begin(),ans.end())

静态数组:

sort(a, a + 3)//该形式应该只能用在数组,不能用在vector

 2.215. 数组中的第K个最大元素 - 力扣(LeetCode)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值