首页 > 学院 > 开发设计 > 正文

佳明面试-洗牌算法

2019-11-06 06:01:59
字体:
来源:转载
供稿:网友

一副牌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]); } }
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表