一副牌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]); } }新聞熱點
疑難解答