Fork me on GitHub

Shuffle an Array

Descritption

https://leetcode.com/problems/shuffle-an-array/description/

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {
public:
Solution(vector<int> nums) {
current = 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> ret;
int size = this->origin.size();
while(size > 0) {
int randomIndex = rand() % size;
ret.push_back(current[randomIndex]);
swap(current, randomIndex, size - 1);
size -= 1;
}
return ret;
}

void swap(vector<int>& vec, int left, int right) {
int temp = vec[left];
vec[left] = vec[right];
vec[right] = temp;
}
private:
vector<int> origin;
vector<int> current;
};

/**
* 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();
*/