Solution 1 - Intermediate Array: Rotate Array in Java
Solution 1 - Intermediate Array: Rotate Array in Java
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]. How many different
ways do you know to solve this problem?
int j=0;
for(int i=k; i<nums.length; i++){
result[i] = nums[j];
j++;
}
Space is O(n) and time is O(n). You can check out the difference between System.arraycopy() and
Arrays.copyOf().
i=0
0 1 2 3 4 5 6
0 1 2 3 4 6 5
...
6 0 1 2 3 4 5
i=1
6 0 1 2 3 5 4
...
5 6 0 1 2 3 4
i=2
5 6 0 1 2 4 3
...
4 5 6 0 1 2 3
Solution 3 - Reversal
Can we do this in O(1) space and in O(n) time? The following solution does.
Assuming we are given {1,2,3,4,5,6} and order 2. The basic idea is:
reverse(arr, 0, a-1);
reverse(arr, a, arr.length-1);
reverse(arr, 0, arr.length-1);
References:
1. Programming Pearls
Related Posts:
1. LeetCode – Next Permutation (Java)
2. LeetCode – 4Sum (Java)
3. LeetCode – Sort Colors (Java)
4. LeetCode – Rotate Image (Java)
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For
example:
<pre><code>
String foo = "bar";
</code></pre>