-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGlobal-and-Local-Inversions.java
78 lines (63 loc) · 1.83 KB
/
Global-and-Local-Inversions.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
class Solution {
public boolean isIdealPermutation(int[] nums) {
int locInv = 0;
int n = nums.length;
for(int i = 0; i < n - 1; i++){
if(nums[i] > nums[i + 1]){
locInv++;
}
}
int globInv = countInv(nums, 0 , n - 1);
return globInv == locInv;
}
public static int countInv(int[] arr, int left, int right){
int ans = 0;
if(left < right){
int mid = (left + right) / 2;
// left sub-half inversions
ans += countInv(arr, left, mid);
// right sub-half inversions
ans += countInv(arr, mid + 1, right);
// remaining left or right inversions
ans += mergeAndCount(arr, left, mid, right);
}
return ans;
}
public static int mergeAndCount(int[] arr, int left, int mid, int right){
int N1 = mid - left + 1;
int N2 = right - mid;
int[] leftArr = new int[N1];
int[] rightArr = new int[N2];
for(int i = 0; i < N1; i++){
leftArr[i] = arr[left + i];
}
for(int j = 0; j < N2; j++){
rightArr[j] = arr[mid + 1 + j];
}
int i = 0, j = 0, k = left, count = 0;
while(i < N1 && j < N2){
if(leftArr[i] <= rightArr[j]){
arr[k] = leftArr[i];
i++;
k++;
}
else{
arr[k] = rightArr[j];
j++;
k++;
count += (N1 - i);
}
}
while(i < N1){
arr[k] = leftArr[i];
i++;
k++;
}
while(j < N2){
arr[k] = rightArr[j];
j++;
k++;
}
return count;
}
}