Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

How to efficiently find three largest numbers of array, in Java?

import java.util.Arrays;
import java.util.PriorityQueue;

public class ThreeLargestNumbers {
	/*
	 * This code finds the three largest numbers
	 * in an array in an efficient manner.
	 * 
	 * Let n be size of the array
	 * 
	 * Time complexity: O(n)
	 * Space complexity: O(1)
	 * 
	 */
	public static void main(String[] args) {
		int[] arr = { 2, 4, 3, 1 };
		int[] threeLargestNbs = findThreeLargestNumbers(arr);
		// The below prints: [2, 3, 4]
		System.out.println(Arrays.toString(threeLargestNbs));
	}

	// Below function finds 3 larges numbers in arr
	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;
	}
}
Comment

PREVIOUS NEXT
Code Example
Java :: java get variable from another class 
Java :: get first letter of string in array java 
Java :: loop through string in java 
Java :: full screen dialog android 
Java :: how to add elements to an array in java dynamically 
Java :: java random unique key 
Java :: Spring boot fix cors problem 
Java :: imageio class java 
Java :: groovy ternary operator short form 
Java :: how to print multiple things in one line java 
Java :: how to get a section of an array in java 
Java :: change button text onclick java 
Java :: java scanner netLine 
Java :: share intent android 
Java :: generate 5 digit random string in java 
Java :: initialize arraylist 
Java :: how to find the sum of an array in java 
Java :: how to write deserlizer java 
Java :: java string to lower case 
Java :: java logger 
Java :: nested for each loop java 
Java :: flow dependency android 
Java :: how to get the smallest number in an array java 
Java :: keytool error: java.io.FileNotFoundException: c:UsersUSER_NAMEupload-keystore.jks (The system cannot find the path specified) 
Java :: from string to double java 
Java :: tableau de classe java 
Java :: sum of a list using for loop in dart 
Java :: string length in java 
Java :: Java print class type 
Java :: get raondom from array java 
ADD CONTENT
Topic
Content
Source link
Name
7+3 =