-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0189-Rotate-array.cs
More file actions
54 lines (42 loc) · 1.24 KB
/
0189-Rotate-array.cs
File metadata and controls
54 lines (42 loc) · 1.24 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
using System;
using System.Collections.Generic;
using System.Text;
namespace Solution._0189.Rotate_array
{
public class _0189_Rotate_array
{
public void Rotate(int[] nums, int k)
{
// additional memory
//int[] res = new int[nums.Length];
//int len = nums.Length;
//for (int i = 0; i < len; i++)
// res[(i + k) % len] = nums[i];
//for (int j = 0; j < len; j++)
// nums[j] = res[j];
// without using any additional memory
if (nums.Length < 2) return;
// ex: 1 2 3 4 5 6 7
k %= nums.Length;
// reverse all, result: 7 6 5 4 3 2 1
Reverse(nums, 0, nums.Length - 1);
// reverse 0~k-1, result: 5 6 7 4 3 2 1
Reverse(nums, 0, k - 1);
// reverse k~nums.length-1
Reverse(nums, k, nums.Length - 1);
}
private void Reverse(int[] nums, int l, int r)
{
int tmp;
while (l < r)
{
// swap
tmp = nums[l];
nums[l] = nums[r];
nums[r] = tmp;
l++;
r--;
}
}
}
}