网站首页 > 精选教程 正文
Given an array, rotate the array to the right by k steps, where k is non-negative.
Follow up:
- Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
- Could you do it in-place with O(1) extra space?
Example 1:
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:
Input: nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
Constraints:
- 1 <= nums.length <= 2 * 104
- -231 <= nums[i] <= 231 - 1
- 0 <= k <= 105
给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。
解题思路:
首先这是一道难度值为简单的题型,注意题目要求最好空间复杂度O(1),即不能定义额外数组,只能在参数数组中修改。
第一种解法比较直观:
根据k来循环嵌套移动数组,时间复杂度为KN
class Solution {
public void rotate(int[] nums, int k) {
int n = nums.length;
for (int i=0; i<k; i++) { //遍历k遍
int last = nums[n-1]; // 保留数组的最后一位
for (int j=n-1; j>=1; j--) { //逆序遍历,除了第一位,将剩余所有数组元素右移
nums[j] = nums[j-1];
}
nums[0] = last; // 将最后一个元素放置第一个位置
}
}
}
第二种解法:
首先考虑如何保证时间复杂度为N?开脑洞。
原始数组: 1 2 3 4 5 6 7
将原始数组反转: 7 6 5 4 3 2 1
将前K个元素反转 : 5 6 7 4 3 2 1
将第N-K个元素反转 : 5 6 7 1 2 3 4
class Solution {
public void rotate(int[] nums, int k) {
k %= nums.length; //为什么要做求余操作? 因为如果k > length,就会出现重复移位,所以求余避免重复移位
reverse(nums, 0, nums.length - 1); //将原始数组反转
reverse(nums, 0, k - 1); //将前K个元素反转
reverse(nums, k, nums.length - 1); //将第N-K个元素反转
}
public void reverse(int[] nums, int start, int end) {
while (start < end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
}
猜你喜欢
- 2024-11-13 面试:聊一聊 Java 数组默认的排序算法,我懵了
- 2024-11-13 golang2021数据格式(6)数组逆置 golang数组转字符串
- 2024-11-13 使用DeepClone沿数组对角线翻转180度
- 2024-11-13 深入理解 JavaScript 数组方法:从零实现 reverse 方法
- 2024-11-13 程序员面试算法题之数组[3],反转整数
- 2024-11-13 Vue短文:如何使用v-for反转数组的顺序?
- 2024-11-13 Java重学—进阶知识 java重点知识回顾
- 2024-11-13 关于数组,你必须要知道的几大算法
- 2024-11-13 python经典案例:将一个数组逆序输出
- 2024-11-13 shell中如何逆序打印数组的内容,或者反转一个数组?
你 发表评论:
欢迎- 最近发表
- 标签列表
-
- nginx反向代理 (57)
- nginx日志 (56)
- nginx限制ip访问 (62)
- mac安装nginx (55)
- java和mysql (59)
- java中final (62)
- win10安装java (72)
- java启动参数 (64)
- java链表反转 (64)
- 字符串反转java (72)
- java逻辑运算符 (59)
- java 请求url (65)
- java信号量 (57)
- java定义枚举 (59)
- java字符串压缩 (56)
- java中的反射 (59)
- java 三维数组 (55)
- java插入排序 (68)
- java线程的状态 (62)
- java异步调用 (55)
- java中的异常处理 (62)
- java锁机制 (54)
- java静态内部类 (55)
- java怎么添加图片 (60)
- java 权限框架 (55)
本文暂时没有评论,来添加一个吧(●'◡'●)