Kth number (with.Java)
This is an article about the โKth number (with.Java)โ problem.
As I solve coding test problems, I look back on the problems I solved and look into different solution methods to get to know myself.
Letโs look at the problem first.
problem
When cutting and sorting from the i-th number to the j-th number of an array, we want to find the k-th number.
For example, if array is [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, k = 3
If you cut the 2nd to 5th positions in the array, you get [5, 2, 6, 3].
Sorting the array from 1 is [2, 3, 5, 6].
The third number in the array from 2 is 5.
When an array array, a two-dimensional array commands with [i, j, k] as elements, is given as a parameter, write a solution function to return the result of applying the operation described above to all elements of commands in an array. Please.
Restrictions
- The length of the array is between 1 and 100.
- Each element of the array is between 1 and 100.
- The length of commands is between 1 and 50.
- Each element of commands has length 3.
Input/Output Example
array | commands | return |
---|---|---|
[1, 5, 2, 6, 3, 7, 4] | [[2, 5, 3], [4, 4, 1], [1, 7, 3]] | [5, 6, 3] |
My solution to the problem
import java.util.Arrays;
class Solution {
public int[] solution(int[] array, int[][] commands) {
int[] answer = new int[commands.length];
for(int i = 0; i < commands.length; i++){
int[] tempArr = Arrays.copyOfRange(array, commands[i][0] - 1, commands[i][1]);
Arrays.sort(tempArr);
answer[i] = tempArr[commands[i][2] - 1];
}
return answer;
}
}
Solved review
The solution method receives an integer array array and a two-dimensional integer array commands as input.
Create an integer array answer to store the results. It is set to the same size as the commands array.
Iterates through the commands array and processes each command.
Each command cuts the array into a specific section, sorts the section, and extracts the value at a specific position.
Use the Arrays.copyOfRange() method to create a new array by copying the corresponding range from the given array.
Sort the copied array using the Arrays.sort() method.
Store the value at position commands[i][2] - 1 in the sorted array into answer[i]. Note that the array index starts from 0, so 1 must be subtracted from the position value of the command.
When all commands are processed, an answer array is returned.
This code solves the problem of cutting and sorting an array according to each instruction, then extracting and returning the value at a specific position.