Repository navigation
Expand file tree
/
Copy pathRotateArrayKtimes.java
More file actions
79 lines (60 loc) · 1.7 KB
/
Copy pathRotateArrayKtimes.java
File metadata and controls
79 lines (60 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package com.abn.dsalgos.datastructure.problems;
/*
Given an integer, rotate array k times based on left or right as passed in parameter
input = [1,2,3,4,5,6,7], k = 5, shift = left
output = [6,7,1,2,3,4,5]
input = [1,2,3,4,5,6,7] k = 4, shift = right
output = [4,5,6,7,1,2,3]
*/
public class RotateArrayKtimes {
/*
public int[] rotateArray(int[] array,int shift) {
int length = array.length;
if(length == 0 || length == 1) {
return array;
}
int[] temp = new int[length];
int x = shift % length;
if(x == 0) {
return array;
}
for(int i= 0; i< length - x;i ++) {
temp[i]= array[i+x];
}
for(int i = length-x; i< length ;i++) {
temp[i]= array[i - (length-x)];
}
return temp;
}
*/
// O(n) time and O(1) space
// shiftSide : true -> left, false -> right
public int[] rotateArray(int[] array, int shift, boolean shiftSide) {
int len = array.length;
if (len == 0 || len == 1) {
return array;
}
int x = shift % len;
if (x == 0) {
return array;
}
reverse(array, 0, len - 1);
if (shiftSide) {
reverse(array, 0, len - x - 1);
reverse(array, len - x, len - 1);
} else {
reverse(array, 0, x - 1);
reverse(array, x, len - 1);
}
return array;
}
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--;
}
}
}