-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRotatebyKStep_189
78 lines (64 loc) · 1.78 KB
/
RotatebyKStep_189
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
Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.
Code not accepted due to huge tc - 1 case failed
My code --
class Solution {
public void rotate(int[] nums, int k) {
int j=0;
int temp = 0;
while (j<k) {
temp = nums[nums.length-1];
for (int i=nums.length-1;i>0;i--){
nums[i]=nums[i-1];
}
nums[0] = temp;
j++;
}
for(int i=0;i<nums.length-1;i++)
System.out.print(nums[i]+",");
System.out.print(nums[nums.length-1]);
}
}
code failed test cases - wrong code -
int arr[] = new int [nums.length];
int i = nums.length-1;
int p = k;
while(k!=0){
arr[--k]=nums[i--];
}
for(int j =0;j<=i;j++)
{arr[p++]=nums[j];}
for(int j=0;j<nums.length;j++)
nums[j]=arr[j];
optimised code - by copilot
public class Solution {
public void rotate(int[] nums, int k) {
int n = nums.length;
k = k % n; // In case k is greater than the length of the array
int[] temp = new int[n];
for (int i = 0; i < n; i++) {
temp[(i + k) % n] = nums[i];
}
for (int i = 0; i < n; i++) {
nums[i] = temp[i];
}
}
}
correct code --
class Solution {
public void rotate(int[] nums, int k) {
int arr[]=new int [nums.length];
k=k%nums.length;
int l=0;
for (int i=nums.length-k;i<nums.length;i++){
arr[l]=nums[i];
l++;
}
for (int i=0;i<nums.length-k;i++){
arr[l]=nums[i];
l++;
}
for (int i=0;i<nums.length;i++){
nums[i]=arr[i];
}
}
}