Skip to content

Commit 9b97974

Browse files
authored
Update shuffle-the-array.cpp
1 parent 055b807 commit 9b97974

File tree

1 file changed

+6
-10
lines changed

1 file changed

+6
-10
lines changed

C++/shuffle-the-array.cpp

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,22 +4,18 @@
44
class Solution {
55
public:
66
vector<int> shuffle(vector<int>& nums, int n) {
7-
static const auto& dest = [](int i, int n) {
7+
static const auto& index = [&n](int i) {
88
return (i < n) ? 2 * i : 2 * (i - n) + 1;
99
};
1010
for (int i = 0; i < nums.size(); ++i) {
11-
if (nums[i] < 0) {
12-
continue;
13-
}
1411
int j = i;
15-
do {
16-
j = dest(j, n);
17-
swap(nums[i], nums[j]);
18-
nums[j] = -nums[j];
19-
} while (j != i);
12+
while (nums[i] >= 0) {
13+
j = index(j);
14+
tie(nums[i], nums[j]) = pair(nums[j], ~nums[i]);
15+
}
2016
}
2117
for (auto& num : nums) {
22-
num = -num;
18+
num = ~num;
2319
}
2420
return nums;
2521
}

0 commit comments

Comments
 (0)