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
- C language: Implementation of dynamic array initialization, insertion, traversal, deletion and destruction
- Exception information: jsonmappingexception: out of start_ ARRAY token
- Java uses class array to report error Exception in thread “main” java.lang.NullPointerException solution
- CreateProcess error = 5, access denied. [How to Solve]
- [Solved] Springboot2.x ElasticSearch Error: availableProcessors is already set to [4], rejecting [4]
- Java error prompt….. cannot be resolved
- [Solved] ZK Connect Error: A JNI error has occurred, please check your installation and try again
- [Solved] asList().add() error: UnsupportedOperationException
- JAVA: Random access file is always garbled
- Ternary operator in Java?: error: not a statement
- [Solved] Hibernate Error: java.lang.StackOverflowError at java.lang.Integer.toString(Integer.java:402)
- How to Solve Mockito mockedStatic NotAMockException Error
- How to Solve RAR Files Extract Error with sevenzipjbinding (Multithread Processing)
- [Solved] IDEA: Internal error (java.lang.UnsupportedClassVersionError)
- [Solved] Initialization of anonymous inner class member variable causes java.lang.stackoverflowerror
- Explicit and implicit conversion of Java data type
- Comparison between ArrayList and HashMap
- How to Solve Java Runtime (class file version 53.0)ERROR
- [Javac compilation exception] javac compilation prompts that the package in jdk cannot be found error: package jdk.internal.org.objectweb.asm does not exist and error: cannot find symbol