Given an array of integers with elements in random order, find the k
largest elements in the array.
Note: There are no duplicate elements in the array.
As the value of k
is greater than the length of the array, we return -1
.
The solution to the problem is to use sorting. Once the array is sorted in descending order, the first k
elements in the array are the k
largest elements in the array.
The steps of the algorithm are as follows:
k
elements in the sorted array.import java.util.Arrays;import java.util.Collections;import java.util.List;import java.util.stream.Collectors;class Main{public static void kLargest(int[] arr, int k){List<Integer> integerList = Arrays.stream(arr).boxed().sorted(Collections.reverseOrder()).collect(Collectors.toList());for(int i=0;i<k;i++)System.out.print(integerList.get(i) + " ");}public static void main(String[] args) {int[] arr = new int[]{8, 4, 1, 9, 2};int k = 3;kLargest(arr, k);}}
kLargest()
that takes an integer array arr
and k
. First we convert the integer array to a list using the streams API. Then the stream is sorted in descending order. Lastly, we print the first k
elements of the sorted list.arr
.k
.kLargest()
function, arr
and k
.