/** * @author lautturi.com * Java example: find three largest numbers in java array */ import java.util.*; import java.io.File; import java.io.FileNotFoundException; public class Lautturi { private static int[] findThreeLargestNumbers(int[] arr) { PriorityQueue<Integer> pq = new PriorityQueue<>(); int[] result = new int[3]; for (int val : arr) { pq.add(val); // Do not allow size of pq exceed 3 if (pq.size() > 3) { pq.remove(); } } // Get the three largest values and store them in result for (int idx = 0; idx < result.length; idx++) { result[idx] = pq.remove(); } return result; } public static void main(String[] args) throws FileNotFoundException { int[] numbers = { 11,4,12,7,55,8,12,8,13,55,12,7 }; int[] result = findThreeLargestNumbers(numbers); System.out.println(Arrays.toString(result)); } }Sour.www:eclautturi.com
output:
[13, 55, 55]