Swift Shuffle an Array - LeetCod

作者: 韦弦Zhy | 来源:发表于2018-12-06 14:33 被阅读0次
LeetCode

题目: Shuffle an Array

给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。

说明:

打乱一个没有重复元素的数组。

示例:

// 以数字集合 1, 2 和 3 初始化数组。

int[] nums = {1,2,3};
Solution solution = new Solution(nums);

// 打乱数组 [1,2,3] 并返回结果。任何 [1,2,3]的排列返回的概率应该相同。

solution.shuffle();

// 重设数组到它的初始状态[1,2,3]。

solution.reset();

// 随机返回数组[1,2,3]打乱后的结果。

solution.shuffle();
方案:

主要是打乱的算法:arc4random_uniform但是leetCode一直报未定义,所以就直接使用Swift 4.2+ 的内置方法了。。。可以参考下面这个Stack Overflowd的回答

代码:

class Solution {
    var num: [Int]
    
    init(_ nums: [Int]) {
        self.num = nums
    }
    
    /** Resets the array to its original configuration and return it. */
    func reset() -> [Int] {
        return self.num
    }
    
    /** Returns a random shuffling of the array. */
    func shuffle() -> [Int] {
        return self.num.shuffled() 
    }
}

/**
 * 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()
 */
 
马上完工了
用Swift开始学习算法中,在LeetCode中开始做初级算法这一章节,将做的题目在此做个笔记,希望有更好方法同学们cue我哦。

相关文章

网友评论

    本文标题:Swift Shuffle an Array - LeetCod

    本文链接:https://www.haomeiwen.com/subject/hvhocqtx.html