Let coding interview become easy - Find second largest element
Maybe you will face it problem when you have an interview for a job with Tech. company.
The problem is "How to find second largest element?", it seems very easy to get result, but you must propose an efficient approach.
If there is a vector that consists {2, 3, 4, 1, 7, 6, 5}
, I delcare two variables as first largest element and second largest element. I initialize variables to INT_MIN. At 13 line, if(input[i]>first)
is true, input[i]
is largest element and pass it to first
after storing a value of first
by second
. Otherwise, compare input[i]
with second
, it checks a current value whether it bigger than second
or not.
Source code
Version 1
1 |
|