Starting with the n th element (with.Java)
Starting with the nth element, we learned how to return a new list from a list of integers, starting with the nth element and ending with the last element.
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 an integer list num_list and an integer n, complete the solution function so that it returns a list containing all elements from the nth to the last element.
Example input and output
num_list: [2, 1, 6]
n: 3
result: [6]
My solution to the problem
class Solution {
public int[] solution(int[] num_list, int n) {
int[] answer = new int[num_list.length - n + 1];
for(int i = n - 1; i < num_list.length; i++){
answer[i - n + 1] = num_list[i];
}
} return answer;
}
}
Solution Description
The solution method inside the Solution class takes two parameters.
The first parameter is an array of integers called num_list, and the second parameter is an integer called n.
Define the size of the array: Size a new array named answer by calculating the length from the nth to the last element of num_list.
The size of the array will be num_list.length - n + 1.
Copy through a loop: Use a for loop to copy the values in num_list from the nth element to the last element into the answer array.
The i variable starts at n - 1 and iterates until it is less than num_list.length, which allows us to handle zero-based indexing in Java.
Return the result: When the copying is complete, we return the answer array. This array contains the values from the nth to the last element of num_list.