leetcode mock Shuffle an Array
1. shuffle算法:
http://www.cnblogs.com/huaping-audio/archive/2008/09/09/1287985.html
注意:我们一般用的是第二种swap的方法;但是第一种直接选择,然后把最末尾一位填上的方法,也是很好的。只是会需要两倍的空间。
2. Random nextInt(bound)参数表示 0-inclusive,bound-exclusive: [0, bound)
package com.company; import java.util.LinkedList; import java.util.List; import java.util.Random; public class Main { private int[] orig; public Main(int[] nums) { orig = nums; } /** Resets the array to its original configuration and return it. */ public int[] reset() { return orig; } /** Returns a random shuffling of the array. */ public int[] shuffle() { int[] ret = orig.clone(); Random rand = new Random(); for (int i=0; i<ret.length; i++) { // int value between 0 (inclusive) and the specified value (exclusive) int r = rand.nextInt(ret.length-i); if (r != ret.length-i-1) { int k = ret[r]; ret[r] = ret[ret.length - i - 1]; ret[ret.length - i - 1] = k; } } return ret; } public static void main(String[] args) { // write your code here System.out.println("Hello"); int []nums = {1,2,3}; Main obj = new Main(nums); int[] param_1 = obj.reset(); int[] param_2 = obj.shuffle(); System.out.printf("param_1: %d, %d, %d\n", param_1[0], param_1[1], param_1[2]); System.out.printf("param_2: %d, %d, %d\n", param_2[0], param_2[1], param_2[2]); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!