Finding largest and second-largest out of N numbers

前端 未结 2 1293
盖世英雄少女心
盖世英雄少女心 2020-12-30 16:14

Given n numbers, how do I find the largest and second largest number using at most n+log(n) comparisons?

Note that it\'s not O(n+log(n)), but really n+log(n) compari

2条回答
  •  萌比男神i
    2020-12-30 16:42

    Is there a problem with this? It's at most 3n comparisons (not counting the i < n comparison). If you count that, it's 4n (or 5n in the second example).

    double first = -1e300, second = -1e300;
    for (i = 0; i < n; i++){
      if (a[i] > first){
        second = first;
        first = a[i];
      }
      else if (a[i] > second && a[i] < first){
        second = a[i];
      }
    }
    

    another way to code it:

    for (i = 0; i < n; i++) if (a[i] > first) first = a[i];
    for (i = 0; i < n; i++) if (a[i] < first && a[i] > second) second = a[i];
    

提交回复
热议问题