Skip to content

Commit 8544f50

Browse files
author
董林
committed
添加数组右移k次的算法
1 parent 6b7739b commit 8544f50

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
package com.crossoverjie.algorithm;
2+
3+
import java.util.Arrays;
4+
5+
/**
6+
* 数组右移K次, 原数组<code> [1, 2, 3, 4, 5, 6, 7]</code> 右移3次后结果为 <code>[5,6,7,1,2,3,4]</code>
7+
*
8+
* 基本思路:不开辟新的数组空间的情况下考虑在原属组上进行操作
9+
* 1 将数组倒置,这样后k个元素就跑到了数组的前面,然后反转一下即可
10+
* 2 同理后 len-k个元素只需要翻转就完成数组的k次移动
11+
*
12+
* @author 656369960@qq.com
13+
* @date 12/7/2018 1:38 PM
14+
* @since 1.0
15+
*/
16+
public class ArrayKShift {
17+
18+
public void arrayKShift(int[] array, int k) {
19+
20+
/**
21+
* constrictions
22+
*/
23+
24+
if (array == null || 0 == array.length) {
25+
return ;
26+
}
27+
28+
k = k % array.length;
29+
30+
if (0 > k) {
31+
return;
32+
}
33+
34+
35+
/**
36+
* reverse array , e.g: [1, 2, 3 ,4] to [4,3,2,1]
37+
*/
38+
39+
for (int i = 0; i < array.length / 2; i++) {
40+
int tmp = array[i];
41+
array[i] = array[array.length - 1 - i];
42+
array[array.length - 1 - i] = tmp;
43+
}
44+
45+
/**
46+
* first k element reverse
47+
*/
48+
for (int i = 0; i < k / 2; i++) {
49+
int tmp = array[i];
50+
array[i] = array[k - 1 - i];
51+
array[k - 1 - i] = tmp;
52+
}
53+
54+
/**
55+
* last length - k element reverse
56+
*/
57+
58+
for (int i = k; i < k + (array.length - k ) / 2; i ++) {
59+
int tmp = array[i];
60+
array[i] = array[array.length - 1 - i + k];
61+
array[array.length - 1 - i + k] = tmp;
62+
}
63+
}
64+
65+
public static void main(String[] args) {
66+
int[] array = {1, 2, 3 ,4, 5, 6, 7};
67+
ArrayKShift shift = new ArrayKShift();
68+
shift.arrayKShift(array, 6);
69+
70+
Arrays.stream(array).forEach(o -> {
71+
System.out.println(o);
72+
});
73+
74+
}
75+
}

0 commit comments

Comments
 (0)