算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 打乱数组,我们先来看题面:
https://leetcode-cn.com/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 class:
- 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]
解题
遍历每个数字,将其与随机位置的数字交换
for(i = 0; i < n; ++i)
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;
}
};
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
上期推文:
LeetCode1-380题汇总,希望对你有点帮助!
LeetCode刷题实战381:O(1) 时间插入、删除和获取随机元素
LeetCode刷题实战382:链表随机节点
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5SYxMTZlNmY0gTYjhzMjZTYmVDZxYjM0QTZyYWO0ETN48CX0JXZ252bj91Ztl2Lc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)