有m长度的数组,从中随机选出n个,一般m远大于n。这样简单的问题乍一看居然没有特别好的办法,后来终于脑子清醒了,给出复杂度为O(n)的算法,java的:

int[] getRandomList(int[] a, int n) {

int[] result = new int[n];

Random ran = new Random();

for (int i=0; i<n; i++) {

int index = ran.nextInt(a.length-i);

result[i] = a[index];

a[index] = a[a.length-i-1];

a[a.length-i-1] = result[i];

}

return result;

}


如果数组不可改变:

int[] getRandomList(int[] a, int n) {

int[] result = new int[n];

Random ran = new Random();

Map<Integer, Integer> indexMap = new HashMap<Integer, Integer>();

for (int i=0; i<n; i++) {

int index = ran.nextInt(a.length-i);

int realIndex = index;

if (indexMap.containsKey(index)) {

realIndex = indexMap.get(index);

}

indexMap.put(index, a.length-i-1);

result[i] = a[realIndex];

}

return result;

}