---恢复内容开始---

Description

Given an array, rotate the array to the right by k steps, where k is non-negative.

Example 1:

Input: [1,2,3,4,5,6,7] and 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: [-1,-100,3,99] and 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]

Note:

  • 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?

问题描述:给定一个长度为n的数组和一个非负整数k,向右旋转k部。

思路,首先这里k是可以大于数组的长度的。我采用最暴力的解法,这种解法效率很低,提交之后只能到13%-85% 效率不固定

public void Rotate(int[] nums, int k) {
k = k % nums.Length;
int[] temp = new int[k];
if(k== nums.Length)
return;
int length = nums.Length;
for(int i = ; i < k; i++)
temp[i] = nums[length - k + i];
for(int i = length - k -; i >=; i--)
nums[i+k]=nums[i];
for(int i = ; i < k; i++)
nums[i]=temp[i];
}

解法二  采用反转的方式,先把所有的数组反转,然后反转前k个元素,再反转后n-k个元素

public class Solution {
public void Rotate(int[] nums, int k) {
k = k % nums.Length;
Reverse(nums, , nums.Length-);
Reverse(nums, , k-);
Reverse(nums, k, nums.Length-);
}
private void Reverse(int[] arr, int start, int end){
while(start < end){
int temp = arr[start];
arr[start]=arr[end];
arr[end]=temp;
start++;
end--;
}
}
}

但是 实测发现,后一种方法效率还不如第一种方法。

最新文章

  1. 让低版本的 Android 项目显示出 Material 风格的点击效果
  2. HTML-meta
  3. HTML 表单总结http://images2015.cnblogs.com/blog/1001203/201607/1001203-20160730200559841-2144892373.png
  4. 预定义的类型“Microsoft.CSharp.RuntimeBinder.Binder”未定义或未导入
  5. HDU 4864 (2014 Multi-University Training Contest 1 )
  6. expunge
  7. spring常用的连接池属性文件配置
  8. 20151209jquery学习笔记Ajax 代码备份
  9. linux case 语句
  10. 数学之路-python计算实战(2)-初遇pypy
  11. 每天一个linux命令(37)--iostat命令
  12. nohup和&amp;后台运行,查看占用端口进程
  13. nodeJS里面的模块
  14. [USACO16OPEN]关闭农场Closing the Farm_Silver
  15. Linux之解决你的网络问题
  16. python数据抓取分析(python + mongodb)
  17. Java学习笔记之——内部类
  18. 洛谷P4438 [HNOI/AHOI2018]道路(dp)
  19. shp与json互转(转载)
  20. 对nginx进行平滑升级

热门文章

  1. 开源图标字体 uiw-iconfont v1.2.6 发布,新增图标
  2. vue,数组循环中src路径下图片总是不展示
  3. docker 安装 jenkins 笔记
  4. php 字符转成数字
  5. CH340电路设计
  6. visual Studio如何使用断点调试程序?
  7. php floor()函数 语法
  8. php abs()函数 语法
  9. Andrdoid中对应用程序的行为拦截实现方式之----从Java层进行拦截
  10. [CSP模拟测试43、44]题解