Skip to content

Commit b4ce071

Browse files
committed
LC#1920 make permutation of given array, O(N) Time, O(N) space
1 parent 3e4cce3 commit b4ce071

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package leetcodeTags.array;
2+
3+
import java.util.Arrays;
4+
5+
public class BuildArrayFromPermutation1920 {
6+
7+
public static int[] buildArray1(int[] nums) {
8+
9+
int[] ans = new int[nums.length];
10+
11+
for (int i = 0; i < nums.length; i++) {
12+
ans[i] = nums[nums[i]];
13+
}
14+
15+
return ans;
16+
}
17+
18+
public static int[] buildArray(int[] nums) {
19+
20+
for (int i = 0; i < nums.length; i++) {
21+
int curr = nums[i];
22+
swap(nums, i, curr);
23+
}
24+
25+
return nums;
26+
}
27+
28+
private static void swap(int[] arr, int i, int j) {
29+
int temp = arr[i];
30+
arr[i] = arr[j];
31+
arr[j] = temp;
32+
}
33+
34+
public static void main(String[] args) {
35+
// int[] result = buildArray(new int[] { 0, 2, 1, 5, 3, 4 });
36+
int[] result = buildArray(new int[] { 5, 0, 1, 2, 3, 4 });
37+
38+
System.out.println(Arrays.toString(result));
39+
}
40+
}

0 commit comments

Comments
 (0)