数据结构与算法---螺旋矩阵、整数反转

博客主要介绍了螺旋矩阵和整数反转两个问题。对于螺旋矩阵,需按顺时针螺旋顺序返回矩阵元素,要定义四个变量并注意行数奇偶;对于整数反转,要将 32 位有符号整数各位数字反转,还提及处理溢出的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

螺旋矩阵

54. 螺旋矩阵
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。

示例 1:输入:

[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

输出: [1,2,3,6,9,8,7,4,5]

示例 2:输入:

[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]

输出: [1,2,3,4,8,12,11,10,9,5,6,7]


思路

需要定义四个变量:
top、bottom、left、right
需要注意的地方:行数为奇数或偶数

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        if(matrix == null) return null;
        List<Integer> array = new ArrayList<>();
        if(matrix.length == 0) return array;
        if(matrix[0].length == 0) return array;

        int top = 0;
        int bottom = matrix.length - 1;
        int left = 0;
        int right = matrix[0].length - 1;

        while(left <= right && top <= bottom){
            for(int i = left; i<=right; i++){
                array.add(matrix[top][i]);
            }
            top++;
            if(left > right || top > bottom) break;
            
            for(int i = top; i<=bottom; i++){
                array.add(matrix[i][right]);
            }
            right--;
            if(left > right || top > bottom) break;

            for(int i = right; i>=left; i--){
                array.add(matrix[bottom][i]);
            }
            bottom--;
            if(left > right || top > bottom) break;

            for(int i = bottom; i>=top; i--){
                array.add(matrix[i][left]);
            }
            left++;
            if(left > right || top > bottom) break;
        }
        return array;
    }
}

整数反转

7. 整数反转

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

示例 1:
输入: 123
输出: 321

示例 2:
输入: -123
输出: -321

示例 3:
输入: 120
输出: 21

注意:
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。


思路

1234
1234 % 10 = 4得到个位数4
1234 / 10 = 123得到剩余的数
123 % 10 = 3得到个位数
result = (((4 * 10) + 3) * 10 + 2) * 10 + 1
result = 4000 + 300 + 20 + 1 = 4321

关于溢出,可以使用long类型,然后返回的时候再强转为int

class Solution {
    public int reverse(int x) {
        long result = 0;
        while(x != 0){
            result = result * 10 + x % 10;
            if(result > Integer.MAX_VALUE) return 0;
            if(result < Integer.MIN_VALUE) return 0;
            x = x/10;
        }
        return (int)result;
    }
}

或者

class Solution {
    public int reverse(int x) {
        int result = 0;
        while(x != 0){
            int pre = result;
            result = pre * 10 + x % 10;
            if((result - x % 10)/10 != pre) return 0;
            x = x/10;
        }
        return result;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值