Up to the nth element (with.Java)
In this article, we’ve learned about the nth element (with.Java).
We’ll do this by solving a coding test problem, reflecting on the problem we solved, and exploring 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 containing all elements of num_list from the first element to the nth element.
Example input and output
num_list | n | result |
---|---|---|
[2, 1, 6] | 1 | [2] |
[5, 2, 1, 7, 5] | 7 | [5, 2, 1] |
My solution to the problem
class Solution {
public int[] solution(int[] num_list, int n) {
int[] answer = new int[n];
for(int i = 0; i < n; i++){
answer[i] = num_list[i];
}
} return answer;
}
}
solution description
int[] answer = new int[n];: Create an integer array answer to store the result. The size of this array is set to n.
for(int i = 0; i < n; i++) : Extract n elements from the beginning of num_list using a loop.
answer[i] = num_list[i];: copy the num_list element at the current index i to the same index in the answer array.
return answer;: Finally return the array answer with n elements from the beginning.