Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve the kth element In subarray with given range in Java?

I Have an array that values in it is :

int[] elements = {4 , 7 , 3 , 6 ,2 ,5 ,1};

The users input is (k,i,j) That K means the Kth index in range (i,j)

If The user's input is (3,0,6) The Answer Must be 3 Cause The 3rd Index in range (0,6) is 3.

How Can I retrieve the Kth index and print The index's value ?

like image 811
ghostDs Avatar asked Jan 20 '26 09:01

ghostDs


1 Answers

One approach could be creating your own function which takes one subarray from the original one using begin and end indexes.

import java.util.Arrays;
public static int[] subArray(int[] array, int beg, int end) {
    return Arrays.copyOfRange(array, beg, end + 1);
}

Then just use below function to access your k - 1 element.

int[] subarray = subArray(arr, beg, end);
System.out.println(subarray[k - 1]);
like image 91
Mihai Alexandru-Ionut Avatar answered Jan 22 '26 23:01

Mihai Alexandru-Ionut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!