//此代码为求数组的小和(数组中每一个数的左边的数比它小的数的总和) //例如 [1,34,322,52] //1左边没有比1小的数,34左边比34小的数为1,322左边比322小的数为1和34,52左边比52小的数为1和34 //将1加上1和34再加上1和34即为这个数组的小和,,下面将用归并排序解决 //归并排序思想也可用于逆序对 public static int smallSum(int[] arr) { if (arr == null || arr.length < 2) { return 0; } return process(arr, 0, arr.length - 1); } public static int process(int[] arr, int l, int r) { if (l == r) { return 0; } int mid = l + ((r - l) >> 1); return process(arr, 1, mid) + process(arr, mid + 1, r) + merge(arr, l, mid, r); } public static int merge(int[] arr, int L, int m, int R) { int[] help = new int[R - L + 1]; int i = 0; int p1 = L; int p2 = m + 1; int res = 0; while (p1 <= m && p2 <= R) { res += arr[p1] < arr[p2] ? (R - p2 + 1) * arr[p1] : 0; help[i++] = arr[p1] < arr[p2] ? arr[p1++] : arr[p2++]; } while (p1 <= m) { help[i++] = arr[p1++]; } while (p2 <= R) { help[i++] = arr[p2++]; } for (i = 0; i < help.length; i++) { arr[L + i] = help[i]; } return res; }
归并排序的问题
最新推荐文章于 2025-01-03 13:56:46 发布