美文网首页lintcode程序员
一个数组中找最大值和最小值

一个数组中找最大值和最小值

作者: 和蔼的zhxing | 来源:发表于2018-01-25 23:02 被阅读29次

这个不是lintcode里的题目,但是感觉很经典,放在这里。
给定一个数组,在这个数组中找到最大值和最小值。
最近在看一点算法书,看到分治法经典的金块问题,实质就是在一个数组中找到最大值和最小值的问题。
我们用分治法来做,先把数据都分成两两一组,如果是奇数个数据就剩余一个一组。
如果是偶数个数据,就是两两一组,第一组比较大小,分别设置为max和min,第二组来了自己本身内部比较大小,用大的和max进行比较,决定是否更新max,小的同样处理,以此类推。
如果是奇数个数据,就把min和max都设为单个的那个数据,其他的类似上面处理。
书上说可以证明,这个是在数组中(乱序)找最大值和最小值的算法之中,比较次数最少的算法。
瞄了一眼书上的写法,还是很简单的,一遍过。

//这是一中分治法,这是在寻找最大值和最小值比较次数最小的方法。
template<class T>
bool MaxAndMinIndex(vector<T> v, int &maxIndex, int &minIndex)
{
    if (v.empty())
        return false;
    if (v.size() == 1)
        maxIndex = minIndex = 0;
    int s = 0;
    if (v.size() % 2 == 1)
    {
        maxIndex = 0;
        minIndex = 0;
    }
    else
    {
        if (v[0] < v[1])
        {
            minIndex = 0;
            maxIndex = 1;
        }
        else
        {
            minIndex = 1;
            maxIndex = 0;
        }
    }
    
    for (s = 2; s < v.size(); s+=2)
    {
        if (v[s] < v[s + 1])
        {
            if (v[s] < v[minIndex])
                minIndex = s;
            if (v[s + 1] > v[maxIndex])
                maxIndex = s + 1;
        }
        else
        {
            if (v[s] > v[maxIndex])
                maxIndex = s;
            if (v[s + 1] < v[minIndex])
                minIndex = s + 1;
        }
    }
    return true;

}

相关文章

网友评论

    本文标题:一个数组中找最大值和最小值

    本文链接:https://www.haomeiwen.com/subject/qwwbaxtx.html