Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c02bfa8

Browse files
feat(problem #88): add shuffle-the-array
1 parent 7c5cc13 commit c02bfa8

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

‎Easy/shuffle-the-array.cs

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
using System.Linq;
2+
3+
internal class Program
4+
{
5+
#region First Approach (Space Complexity O(n))
6+
public static int[] Shuffle_LinearSpaceComplexity(int[] nums, int n)
7+
{
8+
if (nums == null || nums.Length == 0 || nums.Length != (2 * n))
9+
return [];
10+
11+
int[] result = new int[nums.Length];
12+
13+
int resultIndex = 0;
14+
for (int i = 0; (i < nums.Length) && ((i + n) < nums.Length); i++)
15+
{
16+
int x = nums[i];
17+
int y = nums[i + n];
18+
19+
result[resultIndex] = x;
20+
result[resultIndex + 1] = y;
21+
resultIndex += 2;
22+
}
23+
24+
return result;
25+
}
26+
#endregion
27+
28+
#region First Approach (Space Complexity O(1))
29+
public static int[] Shuffle_ConstantSpaceComplexity(int[] nums, int n)
30+
{
31+
if (nums == null || nums.Length == 0 || nums.Length != (2 * n))
32+
return [];
33+
34+
// (1 <= nums[i] <= 1000), so we have to use a multiplier is grater than 1000 and (x + (y * multiplier)) must be less than int.MaxValue
35+
int multiplier = 10000;
36+
37+
// Encoding
38+
for (int i = 0; i < n; i++)
39+
{
40+
int x = nums[i];
41+
int y = nums[i + n];
42+
43+
nums[i] = x + (y * multiplier);
44+
}
45+
46+
// Decoding
47+
for (int i = n - 1; i >= 0; i--)
48+
{
49+
int x = nums[i] % multiplier;
50+
int y = nums[i] / multiplier;
51+
52+
nums[2 * i] = x;
53+
nums[2 * i + 1] = y;
54+
}
55+
56+
return nums;
57+
}
58+
#endregion
59+
60+
private static void Main(string[] args)
61+
{
62+
int[] nums = [2, 5, 1, 3, 4, 7];
63+
var result = Shuffle_ConstantSpaceComplexity(nums, 3);
64+
65+
Console.WriteLine(string.Join(',', result));
66+
}
67+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /