LeetCode:螺旋矩阵

java 复制代码
class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();

        if(matrix == null || matrix.length == 0){
            return null;
        }
        //四个边界
        int top = 0;
        int bottom = matrix.length - 1;
        int left = 0;
        int right = matrix[0].length - 1;

        while(top <= bottom && left <= right){
            for(int i = left; i <=right; i++){
                result.add(matrix[top][i]); 
            }
            top++;

            for(int i = top; i <= bottom; i++){
                result.add(matrix[i][right]);
            }
            right--;
            //额外进行一次判断
            if(top <= bottom && left <= right){
                for(int i = right; i >= left; i--){
                    result.add(matrix[bottom][i]);
                }
                bottom--;
                for(int i = bottom; i >= top; i--){
                    result.add(matrix[i][left]);
                }
                left++;
            }

        }
        return result;
    }
}

这里需要注意第二个判断,防止读取重复数据。

相关推荐
伊玛目的门徒5 小时前
试用leetcode之典中典 二数之和问题
java·算法·leetcode
Jerry5 小时前
LeetCode 226. 翻转二叉树
算法
想做小南娘,发现自己是女生喵6 小时前
【无标题】
数据结构·算法
Kx_Triumphs8 小时前
HDU4348 To the moon(主席树区间修改模板)
算法·题解
旖-旎8 小时前
《LeetCode647 回文子串 || LeetCode 5 最长回文子串》
c++·算法·leetcode·动态规划·哈希算法
轻颂呀9 小时前
约瑟夫环问题
算法
科技大视界11 小时前
投资AI项目,传统尽调不够用了——李章虎律师拆解算法、数据、算力三大雷区
人工智能·算法·数据挖掘
郝学胜-神的一滴11 小时前
算法实战:最小k个数——大顶堆的优雅解法
开发语言·数据结构·c++·python·程序人生·算法·排序算法
Irissgwe11 小时前
算法滑动窗口
数据结构·算法