给你一个整数数组 nums ,设计算法来打乱一个没有重复元素的数组。
实现 Solution class:
Solution(int[] nums) 使用整数数组 nums 初始化对象
int[] reset() 重设数组到它的初始状态并返回
int[] shuffle() 返回数组随机打乱后的结果
class Solution { init(_ nums: [Int]) { } /** Resets the array to its original configuration and return it. */ func reset() -> [Int] { } /** Returns a random shuffling of the array. */ func shuffle() -> [Int] { } } /** * Your Solution object will be instantiated and called as such: * let obj = Solution(nums) * let ret_1: [Int] = obj.reset() * let ret_2: [Int] = obj.shuffle() */
思路:
比如打乱54张牌面试题,先从54张牌中随机选一张,然后放在第0个位置,然后再从后面的53张牌中随机选一张,然后放在第1个位置……直到选够54张牌。
解法:
class Solution { let original: [Int] init(_ nums: [Int]) { self.original = nums } /** Resets the array to its original configuration and return it. */ func reset() -> [Int] { return self.original } /** Returns a random shuffling of the array. */ func shuffle() -> [Int] { var arr = self.original for i in 0 ..< arr.count { arr.swapAt(i, Int.random(in: i ..< arr.count)) } return arr } }
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shuffle-an-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。