一副牌52张,考虑时间复杂度和空间复杂度。
//初始化扑克牌 int[] source = new int[52]; for (int i = 1; i <= 52; i++) { source[i - 1] = i; } int[] res = new int[52]; Random random = new Random(); int index = 0; int lastIndex = source.length - 1; //洗牌开始 while (true) { if (lastIndex == 0) { index = 0; } else { index = random.nextInt(lastIndex); //生成[0,lastIndex]之间的随机数 } Integer value = source[index]; source[index] = source[lastIndex]; res[lastIndex]=value; if (lastIndex == 0) { break; } lastIndex--; } //打印结果 for (int i = 0; i < res.length; i++) { System.out.PRintln(res[i]); } }新闻热点
疑难解答