class Solution { public static int MAXN = 50001; public static int[] help = new int[MAXN]; public static void main(String[] args) { } public static int reversePairs(int[] arr) { return counts(arr, 0, arr.length - 1); } //统计l …… r上反转对的数量,同时计算后变有序 public static int counts(int[] arr, int l, int r) { if (l == r) { return 0; } int mid = l + ((r - l) >> 1); return counts(arr, l, mid) + counts(arr, mid + 1, r) + merge(arr, l, mid, r); } public static int merge(int[] arr, int l, int mid, int r) { int ans = 0; for (int i = l, j = mid + 1; i <= mid; i++) { while (j <= r && (long) arr[i] > (long) arr[j] * 2) { j++; } ans += j - mid - 1; } int i = l ; int a = l; int b = mid + 1; while (a <= mid && b <= r) { help[i++] = arr[a] <= arr[b] ? arr[a++] : arr[b++]; } while (a <= mid) { help[i++] = arr[a++]; } while (b <= r) { help[i++] = arr[b++]; } for (i = l; i <= r ; i++) { arr[i] = help[i]; } return ans; } }
力扣493.翻转对
于 2024-09-09 17:24:28 首次发布