vault backup: 2022-07-10 09:57:15
This commit is contained in:
parent
c17968b7a1
commit
76faef22ff
|
@ -58,6 +58,41 @@ rotate 2 steps to the right: [3,99,-1,-100]
|
|||
|
||||
#### Method 2: Copy
|
||||
|
||||
Watch out for integer overflow.
|
||||
|
||||
#### Method 3: CPP's STL
|
||||
|
||||
|
||||
|
||||
### Solution
|
||||
|
||||
Method 2:
|
||||
```cpp
|
||||
class Solution {
|
||||
void swap(vector<int> &nums, int l, int r) {
|
||||
int temp = nums[l];
|
||||
nums[l] = nums[r];
|
||||
nums[r] = temp;
|
||||
}
|
||||
|
||||
public:
|
||||
void rotate(vector<int> &nums, int k) {
|
||||
int size = nums.size();
|
||||
if (size <= 1) {
|
||||
return;
|
||||
}
|
||||
// Copy
|
||||
k = size - k;
|
||||
while (k < 0) {
|
||||
k += size;
|
||||
}
|
||||
vector<int> ans(nums.size());
|
||||
for (int i = 0; i < size; i++) {
|
||||
ans[i] = nums[(i + k) % size];
|
||||
}
|
||||
for (int i = 0; i < size; i++) {
|
||||
nums[i] = ans[i];
|
||||
}
|
||||
}
|
||||
};
|
||||
```
|
Loading…
Reference in a new issue