forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_922.java
93 lines (89 loc) · 3.04 KB
/
_922.java
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.List;
public class _922 {
public static class Solution1 {
/**
* Space: O(n)
* Time: O(n)
*/
public int[] sortArrayByParityII(int[] nums) {
List<Integer> odds = new ArrayList<>();
List<Integer> evens = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
if (nums[i] % 2 == 0) {
evens.add(nums[i]);
} else {
odds.add(nums[i]);
}
}
int oddIndex = 0;
int evenIndex = 0;
for (int i = 0; i < nums.length; i++) {
if (i % 2 == 0) {
nums[i] = evens.get(evenIndex++);
} else {
nums[i] = odds.get(oddIndex++);
}
}
return nums;
}
}
public static class Solution2 {
/**
* Space: O(1)
* Time: O(n^2)
*/
public int[] sortArrayByParityII(int[] nums) {
for (int i = 0; i < nums.length; i++) {
if (i % 2 == 0 && nums[i] % 2 != 0) {
for (int j = i + 1; j < nums.length; j++) {
if (j % 2 != 0 && nums[j] % 2 == 0) {
int tmp = nums[j];
nums[j] = nums[i];
nums[i] = tmp;
break;
}
}
} else if (i % 2 != 0 && nums[i] % 2 == 0) {
for (int j = i + 1; j < nums.length; j++) {
if (j % 2 == 0 && nums[j] % 2 != 0) {
int tmp = nums[j];
nums[j] = nums[i];
nums[i] = tmp;
break;
}
}
}
}
return nums;
}
}
public static class Solution3 {
/**
* This is the most efficient solution: one implicit condition is that:
* we start with index zero for i, so we look for nums[i] that is not an even number to be swapped with;
* we start with index one for j, so we look for nums[j] that is not an odd number to be swapped with.
* Time: O(n)
* Space: O(1)
*/
public int[] sortArrayByParityII(int[] nums) {
for (int i = 0, j = 1; i < nums.length - 1 && j < nums.length; ) {
if (nums[i] % 2 != 0 && nums[j] % 2 == 0) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
i += 2;
j += 2;
}
while (i < nums.length - 1 && nums[i] % 2 == 0) {
i += 2;
}
while (j < nums.length && nums[j] % 2 != 0) {
j += 2;
}
}
return nums;
}
}
}