1

1 回の反復で、並べ替えられていない配列の 2 番目に最大の要素が必要です。例: 配列は 3 9 8 2 0 -4 87 45 3 2 1 0 です。答えは 45 である必要があります。1 回の反復で max 要素を見つけるのは非常に簡単ですが、同じ反復で 2 番目の max を見つける方法、または定数時間配列のフォート反復の後。

4

3 に答える 3

2
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];
    }
}
于 2014-08-27T04:43:32.413 に答える
1
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
于 2014-08-27T04:34:02.320 に答える
0
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;
    }
}
于 2015-02-10T19:18:36.147 に答える