返回列表 發帖
  1. import java.io.BufferedReader;
  2. import java.io.InputStreamReader;
  3. import java.util.TreeSet;

  4. public class Ch01 {

  5.         BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  6.         String raw[];
  7.         int n;
  8.         TreeSet<Integer> ts=new TreeSet<Integer>();

  9.         Ch01() throws Exception
  10.         {
  11.                 System.out.print("Enter array length: ");
  12.                 n=Integer.parseInt(br.readLine());
  13.                 raw=br.readLine().split(" ");
  14.                 for(int i=0; i<n; i++)
  15.                         ts.add(Integer.parseInt(raw[i]));
  16.                 System.out.print("The result is ");
  17.                 if(ts.size()<3)
  18.                         System.out.println(ts.last());
  19.                 else
  20.                 {
  21.                         int t=ts.floor(ts.last()-1);
  22.                         t=ts.floor(t-1);
  23.                         System.out.println(t);
  24.                 }
  25.         }

  26.         public static void main(String[] args) throws Exception{
  27.                 new Ch01();
  28.         }
  29. }
複製代碼

TOP

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int n, t;
  4. set<int> data;   //set容器的特性:不允許重複 & 遞增排序

  5. int main()
  6. {
  7.     cout<<"Enter array length: ";
  8.     cin>>n;
  9.     for(int i=0; i<n; i++)
  10.     {
  11.         cin>>t;
  12.         data.insert(t);
  13.     }

  14.     cout<<"The result is ";
  15.     if(data.size()<3)
  16.     {
  17.         //原始寫法為 set<int>::reverse_iterator it=data.rbegin();
  18.         //這裡以 auto 來自動判斷其型態
  19.         auto it=data.rbegin();  //抓取最後一個成員的位址
  20.         cout<<*it<<endl;   //取值
  21.     }
  22.     else
  23.     {
  24.         auto it=data.rbegin();
  25.         it++;   //逆向走訪的下一個
  26.         it++;
  27.         cout<<*it<<endl;
  28.     }
  29.     return 0;
  30. }
複製代碼

TOP

返回列表