Reputation: 11
I need the second maximum element in an unsorted array in one iteration. eg: the array is 3 9 8 2 0 -4 87 45 3 2 1 0 The answer should be 45 , its very simple to find max element in one iteration , but how to find the second max in the same iteration , or constant time after the fort iteration of the array.
Upvotes: 1
Views: 2939
Reputation: 1
function MathLib()
{
this.getSecondMax=function(args)
{
var max = 0;
var secondMax = 0;
for(var i=0;i<arguments.length;i++)
{
if(arguments[i]>max)
{
secondMax = max;
max = arguments[i];
}
else
{
if(secondMax<arguments[i])
{
secondMax = arguments[i];
}
}
}
return secondMax;
}
}
Upvotes: 0
Reputation: 198304
for each element:
if element is bigger than max, max shifts to second-max, element becomes max
else if element is bigger than second-max, element becomes second-max
Upvotes: 2
Reputation: 76
int sz = arr.size();
assert(sz >= 2);
int maxElem = arr[0];
int secElem = arr[1];
if (maxElem < secElem) swap(maxElem, secElem);
for (int i = 2; i < sz; ++i) {
if (arr[i] > maxElem) {
secElem = maxElem;
maxElem = arr[i];
} else if (arr[i] == maxElem) {
secElem = maxElem;
} else if (arr[i] < maxElem && arr[i] > secElem)) {
secElem = arr[i];
}
}
Upvotes: 2