打乱数组
打乱一个没有重复元素的数组。
示例:
// 以数字集合 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<int> origin;
public:
Solution(vector<int> nums) {
origin = 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() {
vector<int> res = origin;
int r;
for(int i=0;i<res.size();i++){
r = rand() % (i+1);
if(r!=i)
swap(res[i],res[r]);
}
return res;
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* vector<int> param_1 = obj.reset();
* vector<int> param_2 = obj.shuffle();
*/
思路&问题:
- 先把原始数组保存下来,reset就返回原始数组。shuffle就生成一个[0,nums.size())范围内的随机数,如果不是当前i,就交换次序。循环nums.size()次,就可以打乱数组了
- python中的随机数函数random.randint(取值范围)