标签:m选n
有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;
}
本文出自 “7282813” 博客,请务必保留此出处http://7292813.blog.51cto.com/7282813/1531265
标签:m选n
原文地址:http://7292813.blog.51cto.com/7282813/1531265