Reorder (with.Java)
In this post, we learned how to reorder a list of integers to create a new array by changing the order of the indexes to match a rule.
Weโll do this by solving a coding test problem, reflecting on the problem we solved, and learning about other ways to solve it.
Letโs start with the problem
Problem
Given a list of integers num_list and an integer n, complete the solution function so that it returns a list that divides num_list by the elements after the nth element and the elements up to the nth element, with the elements after the nth element preceded by the elements up to the nth element.
Example input and output
num_list | n | result |
---|---|---|
[2, 1, 6] | 1 | [1, 6, 2] |
[5, 2, 1, 7, 5] | 3 | [7, 5, 5, 2, 1] |
My solution to the problem
import java.lang.reflect.Array;
class Solution {
public int[] solution(int[] num_list, int n) {
int[] answer = new int[num_list.length];
for(int i = n; i < num_list.length; i++){
answer[i - n] = num_list[i];
}
} int k = 0;
for(int j = num_list.length - n; j < num_list.length; j++){
answer[j] = num_list[k++];
}
} return answer;
}
}
Solution
int[] answer = new int[num_list.length];: Create an array answer to store the result.
This array has the same size as num_list.
The first iteration (for(int i = n; i < num_list.length; i++) {): copies the elements from n to the end of the array into the front part of the array answer. This copies the back part of the rotated array to the front part of the answer array.
Second iteration (for(int j = num_list.length - n; j < num_list.length; j++) {): Copies the elements from the front part of the rotated array, num_list.length - n to the end, into the back part of the answer array. This copies the front part of the rotated array to the back part of the answer array.
return answer;: Returns the answer array that finally stores the rotated array.