Rotate Array
来源:互联网 发布:ecshop微商城源码下载 编辑:程序博客网 时间:2024/05/23 13:35
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]
Solution: Requirement: do this problem in O(1) space and in O(n) time.
Step1: Split array into two parts: Before given number and after given number:
Before number: (Array, 0, Array.length - order - 1); After number: (Array, Array.length - order, Array.length - 1);
[1,2,3,4,5,6,7] --> [1,2,3,4,|5,6,7]
Step2: Reverse the two lists
[4,3,2,1,|7,6,5]
Step3: Reverse the whole list
[5,6,7,1,3,3,4]
public void rotate(int[] array, int order) {
if(array == null || order < 0){
throw new IllegalArgumentException("Illegal input");
}
reverse(array, 0, array.length - order - 1);
reverse(array, array.length - order, array.length-1);
reverse(array, 0, array.length - 1);
}
private void reverse(int[] array, int start, int end){
while(start < end){
int temp = array[start];
array[start] = array[end];
array[end] = temp;
start++;
end--;
}
}
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- rotate array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- 【Unity3D】 EventManager事件管理器
- 使用dbms_scheduler调用shell脚本
- LeetBoss
- 侧边栏添加区块-编辑丰富你的Magento边侧栏[添加显示区块]
- Angularjs实践之优化你的$watch
- Rotate Array
- 推荐这六本关于机器学习的书籍,并说说它们的优缺点
- Android Image 倒影
- R语言经典教材
- sql语法:inner join on, left join on, right join on详细使用方法
- [LeetCode] Length of Last Word - 最后一个单词的长度
- mybatis中jsp获取不同表字段显示
- JavaScript显式类型转换与隐式类型转换
- HashMap详解