打亂乙個沒有重複元素的陣列。
示例:
// 以數字集合 1, 2 和 3 初始化陣列。
int[
] nums =
;solution solution =
newsolution
(nums)
;// 打亂陣列 [1,2,3] 並返回結果。任何 [1,2,3]的排列返回的概率應該相同。
solution.
shuffle()
;// 重設陣列到它的初始狀態[1,2,3]。
solution.
reset()
;// 隨機返回陣列[1,2,3]打亂後的結果。
solution.
shuffle()
;
解題思路:國內沒考過,偏數學:「隨機亂置演算法」或者「洗牌演算法」。看看就好。
// 得到乙個在閉區間 [min, max] 內的隨機整數
intrandint
(int min,
int max)
;// 第一種寫法
void
shuffle
(int
arr)
}// 洗牌演算法,或者說隨機亂置演算法的正確性衡量標準是:對於每種可能的結果出現的概率必須相等,也就是說要足夠隨機。
/** 分析洗牌演算法正確性的準則:產生的結果必須有 n! 種可能,否則就是錯誤的。**這個很好解釋,因為乙個長度為 n 的陣列的全排列就有 n! 種,也就是說打亂結果總共有 n! 種。演算法必須能夠反映這個事實,才是正確的。**/
class
solution
/** resets the array to its original configuration and return it. */
vector<
int>
reset()
/** returns a random shuffling of the array. */
vector<
int>
shuffle()
return nums;}}
;/**
* your solution object will be instantiated and called as such:
* solution* obj = new solution(nums);
* vectorparam_1 = obj->reset();
* vectorparam_2 = obj->shuffle();
*/
LeetCode 384 打亂陣列
打亂乙個沒有重複元素的陣列。示例 以數字集合 1,2 和 3 初始化陣列。int nums solution solution new solution nums 打亂陣列 1,2,3 並返回結果。任何 1,2,3 的排列返回的概率應該相同。solution.shuffle 重設陣列到它的初始狀態 ...
Leetcode 384 打亂陣列
打亂乙個沒有重複元素的陣列。示例 以數字集合 1,2 和 3 初始化陣列。int nums solution solution new solution nums 打亂陣列 1,2,3 並返回結果。任何 1,2,3 的排列返回的概率應該相同。solution.shuffle 重設陣列到它的初始狀態 ...
LeetCode 384 打亂陣列
題目 打亂乙個沒有重複元素的陣列。示例 以數字集合 1,2 和 3 初始化陣列。int nums solution solution new solution nums 打亂陣列 1,2,3 並返回結果。任何 1,2,3 的排列返回的概率應該相同。solution.shuffle 重設陣列到它的初始...