Be the first user to complete this post
|
Add to List |
370. Find third largest element in a given array
Objective: Given an array of integers, write an algorithm to find the third largest element in the array.
Example:
Int [] a = { 6, 8, 1, 9, 2, 1, 10} Output: Third largest element - 8 Int [] a = { 6, 8, 1, 9, 2, 1, 10, 10} Output: Third largest element - 9 Int [] a = {6} Output: Invalid Input, array size is less than 3
Approach:
- Take three variables; let's call them first, second and third and mark them as -∞.
- Iterate through the array and for each element (let's call it current),
- Compare it with the first and if first is less, assign the first value to second and second value to third and assign current to first.
- If the above step is not true then current element might be a candidate of the second-highest element, so check if current>second, if yes then assign second value to third and assign current to second.
- If the above step is not true then current element might be a candidate of the third highest element, so check if current>third, if yes then assign current to third.
- At the end print the third, it will third largest element in the array.
See the code below for more understanding.
Output:
Third Largest Element is: 8