日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

Java第三大的数,Java通过排序找出数组第三大数字

發布時間:2025/3/21 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java第三大的数,Java通过排序找出数组第三大数字 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Java通過排序找出數組第三大數字

1 方式一:對數組進行排序并返回第三大數字

通過對數組進行排序并返回第三大數字,我們可以找到java中的第三大數字。讓我們看看完整的示例,以找到java數組中的第三大數字。

/**

* 一點教程網: http://www.yiidian.com

*/

public class ThirdLargestInArrayExample{

public static int getThirdLargest(int[] a, int total){

int temp;

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

{

for (int j = i + 1; j < total; j++)

{

if (a[i] > a[j])

{

temp = a[i];

a[i] = a[j];

a[j] = temp;

}

}

}

return a[total-3];

}

public static void main(String args[]){

int a[]={1,2,5,6,3,2};

int b[]={44,66,99,77,33,22,55};

System.out.println("Third Largest: "+getThirdLargest(a,6));

System.out.println("Third Largest: "+getThirdLargest(b,7));

}

}

以上代碼輸出結果為:

Third Largest:3

Third Largest:66

2 方式二:使用Arrays類找出數組的第三大數字

讓我們看看另一個示例,該示例使用Arrays在Java數組中獲取第三大元素的數字。

/**

* 一點教程網: http://www.yiidian.com

*/

import java.util.*;

public class ThirdLargestInArrayExample1{

public static int getThirdLargest(int[] a, int total){

Arrays.sort(a);

return a[total-3];

}

public static void main(String args[]){

int a[]={1,2,5,6,3,2};

int b[]={44,66,99,77,33,22,55};

System.out.println("Third Largest: "+getThirdLargest(a,6));

System.out.println("Third Largest: "+getThirdLargest(b,7));

}}

以上代碼輸出結果為:

Third Largest: 3

Third Largest: 66

3 方式三:使用Collections獲取數組的第三大數字

/**

* 一點教程網: http://www.yiidian.com

*/

import java.util.*;

public class ThirdLargestInArrayExample2{

public static int getThirdLargest(Integer[] a, int total){

List list=Arrays.asList(a);

Collections.sort(list);

int element=list.get(total-3);

return element;

}

public static void main(String args[]){

Integer a[]={1,2,5,6,3,2};

Integer b[]={44,66,99,77,33,22,55};

System.out.println("Third Largest: "+getThirdLargest(a,6));

System.out.println("Third Largest: "+getThirdLargest(b,7));

}}

以上代碼輸出結果為:

Third Largest: 3

Third Largest: 66

總結

以上是生活随笔為你收集整理的Java第三大的数,Java通过排序找出数组第三大数字的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。