当前位置:网站首页>Leetcode 189. rotation array
Leetcode 189. rotation array
2022-07-29 06:23:00 【Zhangchuming ZCM】
Power button | 189. Rotation array
Title screenshot

Method 1 : Three reverses
Whenever k be equal to n Double speed , Complete a whole cycle , Equivalent to no change .
utilize k=k%n, Remove the invalid changes .
Divide the whole array into two parts , The final result is obtained after three reversals .
for example :nums=[1, 2, 3, 4, 5, 6, 7]
k = 3
Is divided into [1, 2, 3, 4] and [5, 6, 7] Two paragraphs .
Reverse the first paragraph for the first time , have to [4, 3, 2, 1, 5, 6, 7].
Reverse the second paragraph for the second time , have to [4, 3, 2, 1, 7, 6, 5].
Reverse all for the third time , have to [5, 6, 7, 1, 2, 3, 4].
Complexity
Time complexity 
Spatial complexity 
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
n = len(nums)
k %= n
def swap(l, r):
while(l<r):
nums[l], nums[r] = nums[r], nums[l]
l += 1
r -= 1
swap(0, n-1-k)
swap(n-k, n-1)
swap(0, n-1)Complete test code
from typing import List
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
n = len(nums)
k %= n
def swap(l, r):
while(l<r):
nums[l], nums[r] = nums[r], nums[l]
l += 1
r -= 1
swap(0, n-1-k)
swap(n-k, n-1)
swap(0, n-1)
class main:
a = Solution()
nums = [-5, -4, -3, -2, -1]
k = 3
a.rotate(nums,k)
print(nums)
if __name__ == '__main__':
main()With the help of python The slice of completes the inversion
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
n = len(nums)
k %= n
nums[:] = nums[::-1]
nums[:k] = nums[:k][::-1]
nums[k:] = nums[k:][::-1]
Method 2 : Direct use python section
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
n = len(nums)
k %= n
nums[:] = nums[n-k:] + nums[:n-k]Method 3 : Directly create a new array
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
n = len(nums)
ans=[0]*n
for i in range(0, n):
ans[(i+k)%n] = nums[i]
for i in range(0, n):
nums[i] = ans[i]Method four : Circular substitution
Location 0 The element will be placed in (0+k)mod n It's about , Repeated movement in this way will form a moving closed loop .
Of course , This does not completely traverse every element , So the circular movement is completed , After returning to the original position , Just move down one element , Then start such a circular movement .
When can I traverse all the elements ?
Element number n And moving step k The greatest common divisor of is the number of circular movements .
Total number of moving steps = Number of circular movements * Number of moving steps in the ring
So set the inner and outer loops .
The number of outer cycles is the greatest common divisor , Inner circulation moves instead , When the replacement returns to the starting position, exit the inner loop .
import math
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
n = len(nums)
k %= n
count = math.gcd(k, n)
for start in range(0, count):
current = start
prev = nums[start]
while True:
next = (current + k) % n
nums[next], prev = prev, nums[next]
current = next
if next == start:
breakExpand : Custom maximum common divisor
division
def my_gcd(x, y):
while x%y:
x, y = y, x%y
return yiteration
def my_gcd(x, y):
return x if y==0 else self.my_gcd(x, x%y)边栏推荐
- LeetCode #7.整数反转
- Zero basics FPGA (5): counter of sequential logic circuit design (with introduction to breathing lamp experiment and simple combinational logic design)
- 2022 spring move - core technology FPGA development post pen test question (original question and experience)
- Power electronics: single inverter design (matlab program +ad schematic diagram)
- LeetCode #283.移动零
- synchronized八锁现象理解
- 【软件工程之美 - 专栏笔记】21 | 架构设计:普通程序员也能实现复杂系统?
- 2022 spring recruit - Hesai technology FPGA technology post (one or two sides, collected from: Digital IC workers and FPGA Explorers)
- 封装——super关键字
- #6898 变幻的矩阵 题解
猜你喜欢

【软件工程之美 - 专栏笔记】25 | 有哪些方法可以提高开发效率?

LeetCode #14. 最长公共前缀

Jingwei Qili: development of heart rate and blood oxygen module based on hmep060 (1: FPGA sends multi bit instructions)

LeetCode #9.回文数

Jingwei Qili: OLED character display based on hmep060 (and Fuxi project establishment demonstration)

一些工具,插件,软件链接分享给大家~

LeetCode #83. 删除排序链表中的重复元素

2022暑初二信息竞赛学习成果分享2

Ml6 self study notes

LeetCode #3.无重复字符的最长子串
随机推荐
【软件工程之美 - 专栏笔记】“一问一答”第2期 | 30个软件开发常见问题解决策略
Leetcode 283. move zero
Add time series index to two-dimensional table
唯美girls
Huawei cloud 14 day Hongmeng device development -day5 drive subsystem development
LeetCode #13. 罗马数字转整数
简洁代码实现pdf转word文档
Operating system interview questions
Leetcode 1. sum of two numbers
#7110 数字走向2 题解
ML7 self study notes
LeetCode #189.轮转数组
IDEA 实用快捷键 新手必看
LeetCode #7.整数反转
Multithreading and concurrency
LeetCode #283.移动零
【软件工程之美 - 专栏笔记】24 | 技术债务:是继续修修补补凑合着用,还是推翻重来?
数学建模心得
Leetcode 13. Roman numeral to integer
【软件工程之美 - 专栏笔记】19 | 作为程序员,你应该有产品意识