zoukankan      html  css  js  c++  java
  • LeetCode打乱数组Swift

    给你一个整数数组 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
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    在北京的灯中,有一盏是我家的。这个梦何时可以实现?哪怕微微亮。北京就像魔鬼训练营,有能力的留,没能力的走……
  • 相关阅读:
    setInterval的停止与启动
    postgresql常用
    STM32学习笔记(四) RCC外设的学习和理解
    STM32学习笔记(九) 外部中断,待机模式和事件唤醒
    STM32的优先级的理解及其使用
    基于STM32的红外遥控重点解析
    红外协议之NEC协议
    常用运放选型一览表
    运放参数解释及常用运放选型
    算放大器分析----虚短和虚断(转载)
  • 原文地址:https://www.cnblogs.com/huangzs/p/14986869.html
Copyright © 2011-2022 走看看