leetcode54.螺旋矩阵——学习笔记

题目:力扣icon-default.png?t=M0H8https://leetcode-cn.com/problems/spiral-matrix/

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> ans = new ArrayList<Integer>();
        int top = 0;
        int bottom = matrix.length-1;
        int left = 0;
        int right = matrix[0].length-1;
        int count = matrix.length*matrix[0].length;
        while(count>0){
            //右
            for(int i=left ; i<=right&&count>0 ; i++){
                ans.add(matrix[top][i]);
                count--;
            }
            top++;
            //下
            for(int j=top ; j<=bottom&&count>0 ; j++){
                ans.add(matrix[j][right]);
                count--;
            }
            right--;
            //左
            for(int k=right ; k>=left&&count>0 ; k--){
                ans.add(matrix[bottom][k]);
                count--;
            }
            bottom--;
            //上
            for(int l=bottom ; l>=top&&count>0 ; l--){
                ans.add(matrix[l][left]);
                count--;
            }
            left++;
        }
        return ans;
    }
}

 

思路:这道题理解题目不难,但是真要实现出来还是有些困难。解题思路是,一层一层的抽丝剥茧般的读取数据。用top、bottom、left、right四个变量控制边界,按照往右->往下->往左->往上的顺序顺时针走,并用count记录未读取的个数。每一次读取完一层,则修改控制对应边界的变量,直至读完所有数据。

1.声明变量。ans用于存储答案;top为上边界;bottom为下边界;left为左边界;right为右边界;count为未读数据的数量。

List<Integer> ans = new ArrayList<Integer>();
int top = 0;
int bottom = matrix.length-1;
int left = 0;
int right = matrix[0].length-1;
int count = matrix.length*matrix[0].length;

2.按一定的规则(省略号省略的部分则是“一定的规则”)遍历所有元素。

while(count>0){
    //......
}

3.按顺时针(右-下-左-上)的方向逐一读取数据,每读完一个数据则更新count的值,每读完一条边则更新对应的变量(top/bottom/left/right)。读到数据时,将其填入ans列表中去。

//右
for(int i=left ; i<=right&&count>0 ; i++){
    ans.add(matrix[top][i]);
    count--;
}
top++;
//下
for(int j=top ; j<=bottom&&count>0 ; j++){
    ans.add(matrix[j][right]);
    count--;
}
right--;
//左
for(int k=right ; k>=left&&count>0 ; k--){
    ans.add(matrix[bottom][k]);
    count--;
}
bottom--;
//上
for(int l=bottom ; l>=top&&count>0 ; l--){
    ans.add(matrix[l][left]);
    count--;
}
left++;

4.完成上述操作,最后将该列表返回即可。

return ans;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hokachi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值