-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1652- defuse the bomb
77 lines (71 loc) · 1.77 KB
/
1652- defuse the bomb
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
1-->class Solution {
public int[] decrypt(int[] code, int k) {
int n=code.length;
int arr[]=new int[n];
function(arr,k,code);
return arr;
}
static void function(int[] arr,int k,int[] code){
int n=arr.length;
boolean flag=true;
if(k<0){
flag=false;
k=Math.abs(k);
}
int m=0;
for(int i=0;i<arr.length;i++){
if(flag==true){
int l=i;
int p=0;
int val=0;
while(p!=k){
l=l+1;
if(l==n){
l=0;
}
val+=code[l];
p++;
}
arr[m++]=val;
}
else{
int p=0;
int val=0;
int l=i;
while(p!=k){
l=l-1;
System.out.print(l);
if(l==-1){
l=n-1;
}
val+=code[l];
p++;
}
arr[m++]=val;
}
}
}
}
2-->optimizedclass Solution {
public int[] decrypt(int[] code, int k) {
int n = code.length;
int[] arr = new int[n];
// If k is 0, return an array of 0's as no transformation should occur
if (k == 0) {
return arr;
}
// Determine the direction of traversal based on k's sign
int direction = (k > 0) ? 1 : -1;
int range = Math.abs(k); // We only care about the magnitude of k
for (int i = 0; i < n; i++) {
int sum = 0;
// Calculate sum based on the direction and range
for (int j = 1; j <= range; j++) {
int idx = (i + j * direction + n) % n; // Modulo to handle circular behavior
sum += code[idx];
}
arr[i] = sum;
}
return arr;
}
}