资源经验分享LeetCode初级算法--设计问题01:Shuffle an Array (打乱数组)

LeetCode初级算法--设计问题01:Shuffle an Array (打乱数组)

2019-11-09 | |  63 |   0

原标题:LeetCode初级算法--设计问题01:Shuffle an Array (打乱数组)

原文来自:博客园      原文链接:https://www.cnblogs.com/aimi-cn/p/11749062.html


一、引子

这是由LeetCode官方推出的的经典面试题目清单~
这个模块对应的是探索的初级算法~旨在帮助入门算法。我们第一遍刷的是leetcode推荐的题目。
查看完整的剑指Offer算法题解析请点击github链接:
github地址

二、题目

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

示例:

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

1、思路

遍历数组每个位置,每次都随机生成一个坐标位置,然后交换当前位置和随机位置的数字,这样如果数组有n个数字,那么也随机交换了n组位置,从而达到了洗牌的目的。

2、编程实现

python

class Solution(object):

    def __init__(self, nums):
        """
        :type nums: List[int]
        """
        self.data = nums    def reset(self):
        """
        Resets the array to its original configuration and return it.
        :rtype: List[int]
        """
        return self.data    def shuffle(self):
        """
        Returns a random shuffling of the array.
        :rtype: List[int]
        """
        # 方法一:
        # ans = copy.deepcopy(self.data)
        # random.shuffle(ans)
        # return ans
        #方法二
        ans = copy.deepcopy(self.data)        for i in range(len(ans)):
            j = random.randint(i, len(ans)-1)
            ans[i], ans[j] = ans[j], ans[i]        return ans# Your Solution object will be instantiated and called as such:# obj = Solution(nums)# param_1 = obj.reset()# param_2 = obj.shuffle()

本文由博客一文多发平台 OpenWrite 发布!

免责声明:本文来自互联网新闻客户端自媒体,不代表本网的观点和立场。

合作及投稿邮箱:E-mail:editor@tusaishared.com

上一篇:LeetCode初级算法--其他02:有效的括号

下一篇:【笔记】关于N-Way K-Shot 分类问题的理解

用户评价
全部评价

热门资源

  • Python 爬虫(二)...

    所谓爬虫就是模拟客户端发送网络请求,获取网络响...

  • TensorFlow从1到2...

    原文第四篇中,我们介绍了官方的入门案例MNIST,功...

  • TensorFlow从1到2...

    “回归”这个词,既是Regression算法的名称,也代表...

  • 机器学习中的熵、...

    熵 (entropy) 这一词最初来源于热力学。1948年,克...

  • TensorFlow2.0(10...

    前面的博客中我们说过,在加载数据和预处理数据时...