Skip to content

Commit bc60a90

Browse files
Add files via upload
1 parent a8b8866 commit bc60a90

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

Shuffle an Array/Shuffle_an_Array.cpp

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// 附参考链接
2+
// https://mp.weixin.qq.com/s/495KRYJwG0HQDiITY0Jqng
3+
4+
// Runtime: 196 ms, faster than 93.27% of C++ online submissions for Shuffle an Array.
5+
// Memory Usage: 30.1 MB, less than 85.71% of C++ online submissions for Shuffle an Array.
6+
7+
class Solution
8+
{
9+
public:
10+
Solution(vector<int>& nums)
11+
{
12+
data = nums;
13+
size = data.size();
14+
}
15+
16+
/** Resets the array to its original configuration and return it. */
17+
vector<int> reset()
18+
{
19+
return data;
20+
}
21+
22+
/** Returns a random shuffling of the array. */
23+
vector<int> shuffle()
24+
{
25+
vector<int> shuffledata(data);
26+
27+
for (int i = 0; i < size; ++i)
28+
{
29+
int pos = randint(i, size - 1);
30+
swap(shuffledata[i], shuffledata[pos]);
31+
}
32+
33+
return shuffledata;
34+
}
35+
private:
36+
inline int randint(int min, int max)
37+
{
38+
return min + rand() % (max - min + 1);
39+
}
40+
private:
41+
vector<int> data;
42+
int size;
43+
};
44+
45+
/**
46+
* Your Solution object will be instantiated and called as such:
47+
* Solution* obj = new Solution(nums);
48+
* vector<int> param_1 = obj->reset();
49+
* vector<int> param_2 = obj->shuffle();
50+
*/

0 commit comments

Comments
 (0)