Find largest and second largest element in a range

后端 未结 11 2034
情歌与酒
情歌与酒 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:31

    for (e: all elements) {
     if (e > largest) {
       second = largest;
       largest = e;
     } else if (e > second) {
       second = e;
     }
    }
    

    You could either initialize largest and second to an appropriate lower bound, or to the first two items in the list (check which one is bigger, and don't forget to check if the list has at least two items)

提交回复
热议问题