首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

数组的最大的N个值组成的数组

2012-12-22 
求一个数组的最大的N个值组成的数组public class FindTopNValue {public static void main(String[] args)

求一个数组的最大的N个值组成的数组

public class FindTopNValue {public static void main(String[] args) {int[] nums = { 1, 5, 3, 8, 2, 9, 6, 7, 4 };try {int[] result = findTopNValue(nums, 5);for (int i : result) {System.out.print(i + "  ");}} catch (Exception e) {e.printStackTrace();}}private static int[] findTopNValue(int[] nums, int topN) throws Exception {if (nums.length < topN)throw new Exception("top size too big!");int[] result = new int[topN];for (int i = 0; i < topN; i++) {for (int j = 0; j < nums.length; j++) {if (i > 0) {if (nums[j] > result[i] && nums[j] < result[i - 1]) {result[i] = nums[j];}} else {if (nums[j] > result[i]) {result[i] = nums[j];}}}}return result;}}
1 楼 cutesunshineriver 2011-02-28   没有考虑数组里面的整数出现重复的情况。

热点排行