leetcode 刷题记录(高频算法面试题汇总)--打乱数组

打乱数组

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

示例:

// 以数字集合 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();

 

class Solution:

    def __init__(self, nums: List[int]):
        self.origin = nums[:]
        self.res = nums

    def reset(self) -> List[int]:
        """
        Resets the array to its original configuration and return it.
        """
        return self.origin

    def shuffle(self) -> List[int]:
        """
        Returns a random shuffling of the array.
        """
        for i in range(len(self.res)):
            r = random.randint(i,len(self.res)-1)
            self.res[i],self.res[r] = self.res[r],self.res[i]
        return self.res


# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.reset()
# param_2 = obj.shuffle()
class Solution {
private:
    vector origin;
public:
    Solution(vector nums) {
        origin = nums;
    }
    
    /** Resets the array to its original configuration and return it. */
    vector reset() {
        return origin;
    }
    
    /** Returns a random shuffling of the array. */
    vector shuffle() {
        vector res = origin;
        int r;
        for(int i=0;i param_1 = obj.reset();
 * vector param_2 = obj.shuffle();
 */

思路&问题:

  1. 先把原始数组保存下来,reset就返回原始数组。shuffle就生成一个[0,nums.size())范围内的随机数,如果不是当前i,就交换次序。循环nums.size()次,就可以打乱数组了
  2. python中的随机数函数random.randint(取值范围)

你可能感兴趣的:(leetcode)