Q:
Rotate Array Total Accepted: 19161 Total Submissions: 108570 My Submissions Question Solution
Rotate an array of n elements to the right by k steps.
Rotate Array Total Accepted: 19161 Total Submissions: 108570 My Submissions Question Solution
Rotate an array of n elements to the right by k steps.
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].
Here is the code:
/*
Runtime Error Message: Line 5: java.lang.ArrayIndexOutOfBoundsException: 1
Last executed input: [-1], 2
Note: k might be larger num.length - 1.
225 ms
*/
public class Solution {
void reverse(int[] nums, int start, int end) {
while(start < end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
++start;
--end;
}
}
public void rotate(int[] nums, int k) {
k = k % nums.length;
reverse(nums, 0, nums.length - 1 );
reverse(nums, 0, k - 1 );
reverse(nums, k, nums.length - 1 );
}
}
Read More:
- Java: How to Find the Minimum Value from a Random Array by Bubble Sort Method
- Java error prompt….. cannot be resolved
- Explicit and implicit conversion of Java data type
- Ternary operator in Java?: error: not a statement
- JAVA: Random access file is always garbled
- Implementation of retrial mechanism in Java
- Problems and causes of Java’s main function format (public static void main (string args()))
- Java callback function implementation case
- Abstract method and static method of java interface
- Java error: unable to find or load main class (package name in source file)
- JAVA 8: How to Convert List to Map
- Java uses single thread pool to realize multi thread sequential execution (non alternating, non synchronous)
- Initializingbean Interface & Applicationcontextaware Interface in Springboot
- Asynchronous callback case of Java callback function
- The thread implementation of timer in Java
- Three ways of thread sequence alternate execution in Java lock free programming
- The principle and return value of get() function in C language
- Asynchronous processing of HTTP request by Java_ Method 2: through deferredresult
- Springboot controls the startup of rabbitmq through configuration files
- Spring boot uses thread pool to realize asynchronous processing without return and asynchronous processing with return