Find largest and second largest element in a range

后端 未结 11 2008
情歌与酒
情歌与酒 2020-12-10 07:30

How do I find the above without removing the largest element and searching again? Is there a more efficient way to do this? It does not matter if the these elements are dupl

11条回答
  •  春和景丽
    2020-12-10 07:52

    Lets assume you mean to find the two largest unique values in the list.

    If the list is already sorted, then just look at the second last element (or rather, iterate from the end looking for the second last value).

    If the list is unsorted, then don't bother to sort it. Sorting is at best O(n lg n). Simple linear iteration is O(n), so just loop over the elements keeping track:

    v::value_type second_best = 0, best = 0;
    for(v::const_iterator i=v.begin(); i!=v.end(); ++i)
       if(*i > best) {
         second_best = best;
         best = *i;
       } else if(*i > second_best) {
         second_best = *i;
       }
    

    There are of course other criteria, and these could all be put into the test inside the loop. However, should you mean that two elements that both have the same largest value should be found, you have to consider what happens should three or more elements all have this largest value, or if two or more elements have the second largest.

提交回复
热议问题