小和问题和逆序对问题
思路:使用归并排序,每一轮归并后都局部有序,可以利用这个,减少时间复杂度
小和问题
关键代码:
public static int mergeSort(int[] arr, int left, int right) {
if (left == right) {
return 0;
}
int mid = ((right - left) >> 1) + left;
return mergeSort(arr, left, mid) + mergeSort(arr, mid + 1, right) + merge(arr, left, mid, right);
}
public static int merge(int[] arr, int left, int mid, int right) {
int[] help = new int[right - left + 1];
int i = 0;
int p1 = left;
int p2 = mid + 1;
int res = 0;
//每经过一轮归并,数据从小到大排序。在每一轮归并中,计算左边比右边小的数的总和
while (p1 <= mid && p2 <= right) {
if (arr[p1] < arr[p2]) {
res += arr[p1] * (right - p2 + 1);
}
help[i++] = arr[p1] < arr[p2] ? arr[p1++] : arr[p2++];
}
while (p1 <= mid) {
help[i++] = arr[p1++];
}
while (p2 <= right) {
help[i++] = arr[p2++];
}
for (int j = 0; j < help.length; j++) {
arr[left + j] = help[j];
}
return res;
}
逆序对问题
关键代码:
public static int mergeSort(int[] arr, int left, int right) {
if (left == right) {
return 0;
}
int mid = ((right - left) >> 1) + left;
return mergeSort(arr, left, mid) +mergeSort(arr, mid + 1, right) +merge(arr, left, mid, right);
}
public static int merge(int[] arr, int left, int mid, int right) {
int[] help = new int[right - left + 1];
int i = 0;
int p1 = left;
int p2 = mid + 1;
int res=0;
//每经过一轮归并,数据从大到小排序
while (p1 <= mid && p2 <= right) {
if (arr[p1] > arr[p2]) {
for (int j = p2; j <= right; j++) {
res++;
System.out.println(arr[p1] + "," + arr[j]);
}
}
help[i++] = arr[p1] > arr[p2] ? arr[p1++] : arr[p2++];
}
while (p1 <= mid) {
help[i++] = arr[p1++];
}
while (p2 <= right) {
help[i++] = arr[p2++];
}
for (int j = 0; j < help.length; j++) {
arr[left + j] = help[j];
}
return res;
}
Talk is cheap,show me your code.