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

  • 相关阅读:
    Java 开发问题
    include和request
    VC++6.0怎么显示行号
    快速排序
    如何解决虚拟机安装centos无法全屏显示问题!
    详解.NET 4.0新特性Dynamic相关知识
    Action C#
    windbg不常用命令2
    底层枚举 网络连接时的结构
    netbios 和smb
  • 原文地址:https://www.cnblogs.com/NPC-assange/p/9650572.html
Copyright © 2011-2022 走看看