Is it possible to find the 2 largest numbers in an array, and only loop through the collection once?
I had this as an interview question and didn't really get it in time.
Take two variables and initiliaze them with zero. Iterate through each element of the array and compare each number against these two number. If current number is greater than maxOne then maxOne = number and maxTwo = maxOne. Otherwise if it only greater than maxTwo then we only update maxTwo with current number.
Logic To Find First and Second Biggest Number in N Numbers, without using Arrays. First we ask the user to enter length of numbers list. If user enters limit value as 5, then we ask the user to enter 5 numbers. Once the user enters limit value, we iterate the while loop until limit value is 0.
The max() Function — Find the Largest Element of a List. In Python, there is a built-in function max() you can use to find the largest number in a list. To use it, call the max() on a list of numbers. It then returns the greatest number in that list.
It seems pretty straightforward..
int[] nums = { 3, 1, 4, 1, 5, 9, 2, 6 };
int max1 = -1;
int max2 = -1;
foreach (int num in nums)
{
if (num > max1) { max2 = max1; max1 = num; }
else if (num > max2) { max2 = num; }
}
For example:
// 3: max2 = -1; max1 = 3;
// 1: max2 = 1;
// 4: max2 = 3; max1 = 4;
Quick explanation:
In general, you can find the K largest (or smallest) numbers in an array using a single pass for any K. The total time complexity will be O(NK), where N is the size of the array:
Keep a sorted list of numbers that has at most K elements. Walk though the array and for each item:
In the end, the list will contain K largest items, which is what we wanted.
This solution is quite slow, though. Using a self-balancing binary search tree or a skip list, you could get to O(N log K). (Since it's impossible to sort faster than O(N log N) in general case, and this method can be used for sorting the whole array if we set K = N, this looks like the best we can get.)
In the case of K = 2, you don't need all this heavy machinery. Just two variables representing the two positions in the list are enough.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With