zoukankan      html  css  js  c++  java
  • LeetCode--189--旋转数组

    问题描述:

    给定一个数组,将数组中的元素向右移动 个位置,其中 是非负数。

    示例 1:

    输入: [1,2,3,4,5,6,7]k = 3
    输出: [5,6,7,1,2,3,4]
    解释:
    向右旋转 1 步: [7,1,2,3,4,5,6]
    向右旋转 2 步: [6,7,1,2,3,4,5]
    向右旋转 3 步: [5,6,7,1,2,3,4]
    

    示例 2:

    输入: [-1,-100,3,99]k = 2
    输出: [3,99,-1,-100]
    解释: 
    向右旋转 1 步: [99,-1,-100,3]
    向右旋转 2 步: [3,99,-1,-100]

    方法1:1234567  k = 2 step1:54321 76 ;step2:6712345

     1 class Solution(object):
     2     def rotate(self, nums, k):
     3         """
     4         :type nums: List[int]
     5         :type k: int
     6         :rtype: void Do not return anything, modify nums in-place instead.
     7         """
     8         width = len(nums)
     9         if width == 0 or width == 1:
    10             nums = []
    11             return
    12         if width == k:
    13             return
    14         nums[width - k:] = nums[:width-k-1:-1]
    15         nums[:width - k ] = nums[width - k - 1::-1]
    16         nums.reverse()

    官方:

     1 class Solution(object):
     2     def rotate(self, nums, k):
     3         """
     4         :type nums: List[int]
     5         :type k: int
     6         :rtype: void Do not return anything, modify nums in-place instead.
     7         """
     8         n=len(nums)
     9         if n<2 or k==0:
    10             return 
    11         k=k%n
    12         nums[:k],nums[k:]=nums[n-k:],nums[:n-k]

    官方二:

    1 class Solution(object):
    2     def rotate(self, nums, k):
    3         """
    4         :type nums: List[int]
    5         :type k: int
    6         :rtype: void Do not return anything, modify nums in-place instead.
    7         """ 
    8         k = k % len(nums)
    9         nums[:]=nums[-k:]+nums[:-k]

    2018-09-15 11:57:25

  • 相关阅读:
    湖南省队集训 Day 2
    一句话题解(~ 2020.4.9)
    NOIP 2017 宝藏
    NOIP 2017 逛公园
    bzoj 4767 两双手
    Codeforces Gym 101623E English Restaurant
    浅谈Tarjan算法
    Codeforces 1027F Session in BSU
    Codeforces Gym 101623A Ascending Photo
    2018-2019 ICPC, NEERC, Southern Subregional Contest (Online Mirror) Solution
  • 原文地址:https://www.cnblogs.com/NPC-assange/p/9650572.html
Copyright © 2011-2022 走看看