日期:2014-05-20 浏览次数:20578 次
public static int[] max5(List<Integer> lst) { int count = Math.min(5, lst.size()); int[] b = new int[count]; //当然也可以用list来做,但是用数组效率要好一些 for (int i=0; i<count; i++) b[i] = lst.get(i); //相当于递归做法的获得b, //当然递归做法是获得lst的后5个元素,这里是前5个元素,获得后5个元素用lst.size()-count+i就可以了 for (int i=count; i<lst.size(); i++) { int a = lst.get(i); //这里相当于1L的递归做法的 a = lst.remove(0); for (int j=0; j<count; j++) { if (a > result[j]) { //相当于交换a和b的某个位置的数据 int t = result[j]; b[j] = a; //这里就相当于1L的lst.set(i, a) a = t; } } } return b; }
------解决方案--------------------
1L是对的
用数组的话会更快点
import java.util.Arrays; public class MyTop { static final int[] NUMS = new int[]{12,127,85,66,27,34,15,344,156,344,29,47}; static final int SIZE = 5;//前5个最大数 static int[] TOPS = new int[SIZE];//存放最大值的数组 public static void main(String[] args) { long start = System.nanoTime();//开始 find(NUMS.length, SIZE);//获取最大数 System.out.println(Arrays.toString(TOPS));//打印 long end = System.nanoTime();//结束 System.out.println("time = " + (end - start) / 1e9 + " seconds");//输出时间 } static void find(int total,int size){ //前5个数直接存入数组 for(int i = 0;i < size;++i){ TOPS[i] = NUMS[i]; } setMin(); for(int i = size;i < total;++i){ //如果当前数比arr[0]大,将arr[0]替换为num,再获取最小值放入arr[0] if(NUMS[i] > TOPS[0]){ TOPS[0] = NUMS[i]; setMin(); } } } static void setMin(){ int min = TOPS[0]; int index = 0; for(int i = 1;i < TOPS.length;i++){ if(TOPS[i] < min){ min = TOPS[i]; index = i; } } int temp = TOPS[0]; TOPS[0] = TOPS[index]; TOPS[index] = temp; } }
------解决方案--------------------
/** * 取得数组中最大的子数组</br> * 在长数组中取得前N个值,作为最大的子数组,如果遇到后面的数比子数组中最小值小,则将此值设入子数组中 */ public class MaxSubArray { private int[] ints = null; private int count = 1; public MaxSubArray(int[] ints) { this.ints = ints; } public MaxSubArray(int[] ints, int count) { this.ints = ints; this.count = count; } public int[] getMaxArray() { int[] mis = new int[count]; System.arraycopy(ints, 0, mis, 0, count); Info info = min(mis); for (int i = count; i < ints.length; i++) { if (ints[i] > info.min) { mis[info.point] = ints[i]; info = min(mis); } } Arrays.sort(mis); return mis; } private Info min(final int[] ints) { Info info = new Info(); info.min = ints[0]; info.point = 0; for (int i = 1; i < ints.length; i++) { if (info.min > ints[i]) { info.min = ints[i]; info.point = i; } } return info; } private class Info { private int min; private int point; } }