日期:2014-05-20  浏览次数:20732 次

一个面试题,不知道怎么做
有一个字符数组有{ 'a ', 'b ', 'c ', 'd ', 'e '},要求随机输出字符序列(字符不能重复)如:baecd
要求:时间复杂度O(n),C++或Java实现

------解决方案--------------------
就是乱序一下嘛
import java.util.*;

public class Test44 {

public static void main(String[] args) {
// TODO Auto-generated method stub
Random rnd = new Random();
char[] arr = { 'a ', 'b ', 'c ', 'd ', 'e ' };
for (int i = arr.length; i > 1; i--)
swap(arr, i - 1, rnd.nextInt(i));
System.out.println(new String(arr));
}

static void swap(char[] arr, int i, int j) {
char tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}

要是犯懒,直接转List,然后用Collections的shuffle,一样的
------解决方案--------------------
import java.util.ArrayList;

public class Atest2 {

public static void main(String args[]){

ArrayList sList = new ArrayList();
sList.add( "a ");
sList.add( "b ");
sList.add( "c ");
sList.add( "d ");
sList.add( "e ");
int t = 5;
String s = " ";
while(sList.size()> 0){

double d = Math.random();
int i = (int)(d*t);
s += (String)sList.get(i);
sList.remove(i);
t--;

}
System.out.print(s);

}


}

ou shi cai niao~~~~
------解决方案--------------------
时间复杂度O(n), ...不懂..

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;


public class TestRandom {
public static void main(String[] args){
List list = new ArrayList();
list.add( "a ");
list.add( "b ");
list.add( "c ");
list.add( "d ");
list.add( "e ");
System.out.println(list);
Collections.shuffle(list,new Random());
System.out.println(list);
}
}