给你一个整数数组 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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
原文地址:https://www.cnblogs.com/huangzs/p/14986869.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。