-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuildArrayFromPermutation1920.java
More file actions
40 lines (32 loc) · 1.27 KB
/
BuildArrayFromPermutation1920.java
File metadata and controls
40 lines (32 loc) · 1.27 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
public class BuildArrayFromPermutation1920 {
/*
* Given a zero-based permutation nums (0-indexed), build an array ans of the same length,
* where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it.
A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive).
*/
//solve it without using an extra space
class Solution {
public int[] buildArray(int[] nums) {
int n = nums.length;
for (int i = 0; i < n; i++) {
nums[i] = nums[i] + (nums[nums[i]] % n) * n;
System.out.print(nums[i] + " ");
}
System.out.println("");
for (int i = 0; i < n; i++) {
nums[i] = nums[i] / n;
System.out.print(nums[i] + " ");
}
System.out.println("");
return nums;
}
}
public static void main(String[] args) {
Solution solution = new BuildArrayFromPermutation1920().new Solution();
int[] nums = {0, 2, 1, 5, 3, 4};
int[] result = solution.buildArray(nums);
for (int num : result) {
System.out.print(num + " ");
}
}
}