189. Rotate Array -- Python

本文介绍了一种将数组元素向右旋转k步的操作,并提供了两种不同的Python实现方案。一种是通过循环插入和删除元素来完成旋转,另一种则是利用切片操作简化代码。

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

189. Rotate Array

Rotate an array of n elements to the right by k steps.

For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].

Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

思路:
就是移动 k 位元素到列表的左端。第一次提交没有考虑到 k 的值比列表长度还大的情况,第二版中加了一个 if 语句判断。

代码:

class Solution:
    def rotate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        if k <len(nums):
            for i in range(k):
                nums.insert(i,nums[-k+i])
                del nums[-k+i]
        else:
            self.rotate(nums,k%len(nums))

题目中提到了可以尝试采用多种方法,所以也参考了一下别人的思路,很简洁。
参考代码1:

class Solution:
    def rotate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        k = k % len(nums)
        nums[:] = nums[-k:] + nums[:-k]

复习收获:
使用list存储数据时,按索引访问元素很快,但是插入和删除元素就很慢了,因为list是线性存储,数据量大的时候,插入和删除效率很低。deque是为了高效实现插入和删除操作的双向列表,适合用于队列和栈:

from collections import deque
>>> q = deque(['a', 'b', 'c'])
>>> q.append('x')
>>> q.appendleft('y')
>>> q
deque(['y', 'a', 'b', 'c', 'x'])

上面可得:
deque除了实现list的append()和pop()外,还支持appendleft()和popleft(),这样就可以非常高效地往头部添加或删除元素。

### 使用 `scipy.ndimage.rotate` 进行图像旋转 `scipy.ndimage.rotate` 是 SciPy 库中的一个函数,用于对多维数组(通常是图像数据)执行旋转操作。该方法允许指定角度以及插值方式来实现高质量的旋转效果。 以下是关于如何使用 `scipy.ndimage.rotate` 的详细介绍: #### 函数签名 ```python scipy.ndimage.rotate(input, angle, axes=(-1, -2), reshape=True, output=None, order=1, mode='constant', cval=0.0, prefilter=True) ``` - **input**: 输入数组(通常是一个二维或三维的 NumPy 数组表示的图像)。 - **angle**: 顺时针方向的角度值(单位为度数)。如果希望逆时针旋转,则输入负值[^4]。 - **axes**: 定义平面内的两个轴,在此平面上进行旋转,默认为最后两轴 (-1 和 -2),适用于大多数二维图像场景。 - **reshape**: 如果设置为 True,则输出数组会调整大小以适应整个旋转后的图像;否则保持原始尺寸并可能裁剪部分内容[^5]。 - **order**: 插值顺序,范围是从 0 到 5。常用的选项有: - 0: 最近邻插值 - 1: 双线性插值(默认) - 3: 三次样条插值 - **mode**: 边界填充模式,可选参数包括 'reflect'、'constant'、'nearest' 等[^6]。 - **cval**: 当边界填充模式为 'constant' 时使用的常数值,默认为 0.0。 - **prefilter**: 是否应用预滤波器优化高阶插值的效果,仅当 `order > 1` 时有效。 #### 示例代码 下面展示了一个简单的例子,说明如何加载一张图片并通过 `scipy.ndimage.rotate` 对其进行旋转处理: ```python import numpy as np from scipy import ndimage import matplotlib.pyplot as plt from PIL import Image # 加载测试图像 img = Image.open('example.jpg') # 替换为你自己的文件路径 array_img = np.array(img) # 执行90度逆时针旋转 rotated_array = ndimage.rotate(array_img, angle=-90, reshape=True, order=1, mode='constant') # 显示原图与旋转后的结果对比 fig, ax = plt.subplots(1, 2, figsize=(10, 5)) ax[0].imshow(array_img) ax[0].set_title("Original Image") ax[1].imshow(rotated_array.astype(np.uint8)) # 转回整型以便显示 ax[1].set_title("Rotated Image (-90 degrees)") plt.show() ``` 上述脚本中演示了从本地读取一幅 JPEG 图像作为输入源,并调用 `ndimage.rotate()` 实现特定角度下的变换过程[^7]。 #### 注意事项 尽管 Pillow(PIL) 提供了一些基础功能如缩放(resize)、裁切(crop)和简单旋转变换(rotation)[^1],但对于更复杂的几何转换或者需要精确控制参数的应用场合来说,SciPy 中基于 N-Dimensional Array 处理能力所提供的工具无疑更加灵活强大。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值