(LeetCode)Rotate Array --- 逆置数组
来源:互联网 发布:视频直播源码 编辑:程序博客网 时间:2024/06/02 05:15
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.
[show hint]
Hint:
Could you do it in-place with O(1) extra space?
Could you do it in-place with O(1) extra space?
Related problem: Reverse Words in a String II
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
解题分析:
对于这个可以利用分治方法,可以利用给出的 k 值将数列分成两部分,
分别对其中的每一部分进行逆置,然后再把整个逆置一下。
实现逆置的算法原理:
a ^= b
b ^= a
a ^= b
# -*- coding:utf-8 -*-__author__ = 'jiuzhang'class Solution(object): def rotate(self, nums, k): n = len(nums) k %= n self.reverse(nums, 0, n - k) self.reverse(nums, n - k, n) self.reverse(nums, 0, n) def reverse(self, nums, start, end): for x in range(start, (start + end) / 2): nums[x] ^= nums[start + end - x - 1] nums[start + end - x - 1] ^= nums[x] nums[x] ^= nums[start + end - x - 1]
0 0
- (LeetCode)Rotate Array --- 逆置数组
- LeetCode 189 Rotate Array(旋转数组)
- LeetCode 189 Rotate Array(旋转数组)
- LeetCode 189. Rotate Array(旋转数组)
- leetcode:Rotate Array旋转数组
- 【LeetCode】Rotate Array 旋转数组
- Rotate Array 数组旋转 leetcode
- leetcode Rotate Array 旋转数组
- 1.1数组和链表:189. Rotate Array(Leetcode)
- LeetCode Rotate Array(数组的旋转)
- leetcode 189. Rotate Array-旋转数组
- LeetCode#189. Rotate Array(数组循环移位)
- leetcode 189. Rotate Array旋转数组
- LeetCode(189) Rotate Array
- [leetcode][array] Rotate Array
- LeetCode之Rotate Array(C++)
- [Leetcode]Rotate Array java(三种)
- Leetcode:189. Rotate Array(JAVA)
- 模型基图像编码
- sg函数+nim博弈+打表_______A Simple Nim(hdu 5795 2016多校第六场)
- Qt标准对话框实现
- UIAlertController + UIPickerView完美结合
- zlib
- (LeetCode)Rotate Array --- 逆置数组
- Android Proguard混淆器
- POJ1094——Sorting It All Out
- spring lookup-method和replace-method本质
- UIViewAnimationOptions的一些枚举类型
- 153.leetcode Find Minimum in Rotated Sorted Array(medium)[有序数组 二分查找]
- HDU 1438 钥匙计数之一 递推+组合 简洁的做法
- 大数运算-(加、减、乘)
- Android Studio 快捷键简介