Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
76 lines (49 loc) · 2.1 KB

File metadata and controls

76 lines (49 loc) · 2.1 KB
Copy raw file
Download raw file
Outline
Edit and raw actions

Lesson_2 Arrays 数组

Rotate an array to the right by a given number of steps.
  • P2.1 旋转

数组旋转给定次数

由N个整数组成的数组A。数组的一次旋转就是每个元素均向右移动一个位置,数组的最后一个元素移动到第一个位置。

例如,数组A=[3,8,9,7,6],经过1次的循环旋转就为[6,3,8,9,7],经过2次的循环旋转就变为[7, 6, 3, 8, 9]。

编写函数:

def solution(A, K)

给定一个由N个整数组成的数组A和一个整数K,则返回一个旋转K次的数组。

例如,给定A=[3、8、9、7、6],K=3,函数应返回[9、7、6、3、8]。

三次旋转如下:

[3,8,9,7,6]->[6,3,8,9,7]

[6,3,8,9,7]->[7,6,3,8,9]

[7,6,3,8,9]->[9,7,6,3,8]

例如,给出A=[0, 0, 0],K=1,函数应返回[0,0,0];给出A=[1,2,3,4],K=4,函数应返回[1、2、3、4]。

假定:

  1. N和K是范围0至100内的整数;
  2. 数组A的每个元素都是[-1000,1000]内的整数;
  3. 主要考察正确性,算法的性能不是重点;
  • 解题思路

    计算每个元素移动后的索引值,对于一个长度为N的数组,只要KmodN的值相同,结果就是一样的。

  • Python3代码

# -*- coding:utf-8 -*-
# &Author  AnFany
# Lesson 2:Arrays
# P 2.1 CyclicRotation


def solution(A, K):
    """
    返回数组A经过K次旋转后的数组
    :param A: 数组
    :param K: 旋转次数
    :return: 旋转后的数组
    """
    length = len(A)
    new_list = A.copy()
    if K == 0 or length == K or length == 0:
        return new_list
    else:
        times = K % length
        for index, value in enumerate(A):
            new_list[(times + index) - length] = value
        return new_list
  • 结果

image

Morty Proxy This is a proxified and sanitized view of the page, visit original site.