區間K大數尋找 Java 藍橋杯ALGO-1

來源:互聯網
上載者:User

標籤:com   藍橋杯   尋找   有一個   函數   scanner   圖片   一個   答案   

 1 import java.util.Arrays; 2 import java.util.Scanner; 3  4 public class Main { 5     public static void main(String[] args) { 6     Scanner aScanner = new Scanner(System.in); 7     int n= aScanner.nextInt();   //讀第一個 8     long a[] = new long[n];      //存放數組 9     long b[] = new long[n];      //備用數組10     11     for(int i=0;i<n;i++)12     {13         a[i] = aScanner.nextInt();14     }15     int m = aScanner.nextInt();16     int []l = new int[1001];17     int []r = new int[1001];18     int []k = new int[1001];19     for(int i=0;i<m;i++)20     {21         l[i] = aScanner.nextInt();22         r[i] = aScanner.nextInt();23         k[i] = aScanner.nextInt();24         for(int j=l[i]-1;j<r[i];j++)25         {26             b[j-l[i]+1] = a[j];27         }28         Arrays.sort(b);29         System.out.println(b[b.length-k[i]]);30         Arrays.fill(b, ‘\0‘);31         32     }33     }34 }

  剛開始做的時候使用的二維數組,使用冒泡排序,但涉及到了三層迴圈,最後雖然結果出來了,但是運行逾時。

  於是就需求更最佳化的方法,後來參考網上的標準答案後有一個排序函數可以用sort()函數,直接使用Arrays.sort()函數對數組進行從小到大的排序,每次得出結果後直接輸出。

同時迴圈一次後需要對結果進行清空,我使用的是Arrays.fill()函數,用‘\0’來填充,但也有不足的地方,會在清空後都是0的形式存在,數組的長度沒有變化,所以需要我之後進一步改進,最後的評測結果仍舊有一個運行逾時!!,僅供參考

區間K大數尋找 Java 藍橋杯ALGO-1

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.