-
Notifications
You must be signed in to change notification settings - Fork 286
Expand file tree
/
Copy pathSortArrayByParityII.java
More file actions
29 lines (28 loc) · 880 Bytes
/
SortArrayByParityII.java
File metadata and controls
29 lines (28 loc) · 880 Bytes
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
class Solution {
// TC : O(n)
// SC : O(1)
public int[] sortArrayByParityII(int[] nums) {
int oddNoAtEvenIndex= 0;
int evenNoAtOddIndex = 1;
int n = nums.length;
while (oddNoAtEvenIndex < n && evenNoAtOddIndex < n) {
while (oddNoAtEvenIndex < n && nums[oddNoAtEvenIndex] % 2 == 0) {
oddNoAtEvenIndex += 2;
}
while (evenNoAtOddIndex < n && nums[evenNoAtOddIndex] % 2 == 1) {
evenNoAtOddIndex += 2;
}
if (evenNoAtOddIndex < n && oddNoAtEvenIndex < n) {
swap(nums, oddNoAtEvenIndex, evenNoAtOddIndex);
}
}
return nums;
}
private void swap(int[] nums, int i, int j) {
if(i!=j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
}