BTOJ 最值问题

思路:

  • 使用算法库中的sort函数排序

  • 最后一个值必是最大值

  • 从后向前比较找到的第一个小于最大值的数即使次大值数

  • 依次可以找打第k大值

C++题解:

#include<iostream>

#include<algorithm>

using namespace std;

int main()

{   int n;

    cin>>n;

    while(n-- >0){

        int len;

        cin>>len;

        int nums[len];

        for(int i=0;i<len;i++)

            cin>>nums[i];//记录所有数值

        sort(nums, nums+len);//从小到大排序

        int maxVal=nums[len-1], secMaxVal;

        for(int j=len-1;j>=0;j--){

            if(nums[j] < maxVal){//比较找到次大数值

                secMaxVal = nums[j];

                break; }}

        cout<<maxVal<<" "<<secMaxVal<<endl;}

    return 0;} 

相关文章:

  • 2022-12-23
  • 2021-07-29
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-11
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-07-30
  • 2022-12-23
  • 2022-12-23
  • 2021-10-12
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案