LeetCode之Rotate Array

简介: LeetCode之Rotate Array

1、题目

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]


Related problem: Reverse Words in a String II


Credits:

Special thanks to @Freezen for adding this problem and creating all test cases.



2、结题思路

1、先得到有效的k,

2、反转所有数组

3、反转下标从0到k的数组

4、 反转下标从k到length - 1的数组


3、代码实现

class Solution {
  public void rotate(int[] nums, int k) {
        if (nums == null || nums.length == 0 || k <= 0)
          return;
        int length = nums.length;
        int lastK = 0;
        if (k < length)
          lastK = k;
        else 
          lastK = k % length;
        if (lastK == 0)
            return;
        change(nums, length);
        change(nums, lastK);
        int i = lastK, j = length - 1;
        while (i < j) {
          int temp = nums[i];
          nums[i] = nums[j];
          nums[j] = temp;
          i++;
          j--;
        }
    }
    public void change(int[] nums, int length) {
      for (int i = 0; i < length / 2; ++i) {
          int temp = nums[i];
          nums[i] = nums[length - i - 1];
          nums[length - i - 1] = temp;
      }
    }
}
相关文章
|
6月前
Leetcode Find Minimum in Rotated Sorted Array 题解
对一个有序数组翻转, 就是随机取前K个数,移动到数组的后面,然后让你找出最小的那个数,注意,K有可能是0,也就是没有翻转。
19 0
LeetCode contest 200 5476. 找出数组游戏的赢家 Find the Winner of an Array Game
LeetCode contest 200 5476. 找出数组游戏的赢家 Find the Winner of an Array Game
|
算法 Python
LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree
LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree
|
算法 测试技术
LeetCode 88. 合并两个有序数组 Merge Sorted Array
LeetCode 88. 合并两个有序数组 Merge Sorted Array
|
人工智能 索引
LeetCode 1013. 将数组分成和相等的三个部分 Partition Array Into Three Parts With Equal Sum
LeetCode 1013. 将数组分成和相等的三个部分 Partition Array Into Three Parts With Equal Sum
LeetCode 189. 旋转数组 Rotate Array
LeetCode 189. 旋转数组 Rotate Array
|
算法 Python
LeetCode 410. Split Array Largest Sum
给定一个非负整数数组和一个整数 m,你需要将这个数组分成 m 个非空的连续子数组。设计一个算法使得这 m 个子数组各自和的最大值最小。
107 0
LeetCode 410. Split Array Largest Sum
|
11天前
|
Python
使用array()函数创建数组
使用array()函数创建数组。
14 3
|
3月前
|
JavaScript 前端开发
总结TypeScript 的一些知识点:TypeScript Array(数组)(下)
一个数组的元素可以是另外一个数组,这样就构成了多维数组(Multi-dimensional Array)。
|
3月前
|
存储 JavaScript 前端开发
总结TypeScript 的一些知识点:TypeScript Array(数组)(上)
数组对象是使用单独的变量名来存储一系列的值。

热门文章

最新文章