算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !今天和大家聊的问题叫做 打乱数组,我们先来看题面:https:///problems/shuffle-an-array/Given an integer array nums, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling. 给你一个整数数组 nums ,设计算法来打乱一个没有重复元素的数组。Solution(int[] nums) 使用整数数组 nums 初始化对象 int[] reset() 重设数组到它的初始状态并返回 int[] shuffle() 返回数组随机打乱后的结果
示例输入 ["Solution", "shuffle", "reset", "shuffle"] [[[1, 2, 3]], [], [], []] 输出 [null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]
解释 Solution solution = new Solution([1, 2, 3]); solution.shuffle(); // 打乱数组 [1,2,3] 并返回结果。任何 [1,2,3]的排列返回的概率应该相同。例如,返回 [3, 1, 2] solution.reset(); // 重设数组到它的初始状态 [1, 2, 3] 。返回 [1, 2, 3] solution.shuffle(); // 随机返回数组 [1, 2, 3] 打乱后的结果。例如,返回 [1, 3, 2] 解题 swap(ans[i], ans[rand()%n]);class Solution { vector<int> origin; vector<int> ans; public: Solution(vector<int>& nums) { origin = ans = nums; } /** Resets the array to its original configuration and return it. */ vector<int> reset() { return origin; } /** Returns a random shuffling of the array. */ vector<int> shuffle() { int n = origin.size(),i; for(i = 0; i < n; ++i) swap(ans[i], ans[rand()%n]); return ans; } }; 好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
|