逆序对问题
- 题目:所谓逆序对问题就是,在一个数组中,左边的数如果比右边的数大,则这两个数构成一个逆序对
- 举例:
1 3 4 2 5
❤️
<1,3>、<1,4>、<1,2>、<1,5>、< 3,4>、< 3,5>、<4,5>、<2,5>
❤️
代码实现
普通的暴力破解为:N + N-1+ N-2 + N-3 + ···+ 1 时间复杂度为:O(N^2)
借助归并排序可以实现时间复杂度为:O(N*logN)
归并排序详解
package LeetCode;
/**
* @Description:
* @PackageName: LeetCode
* @ClassName: reversePair
* @Author: Y-peak
* @Date: 2021.08.28 00:08 星期六
*/
public class ReversePair {
public static void reversePair(int[] arr){
if(arr == null || arr.length < 2){
return;
}
process(arr, 0 , arr.length-1);
}
public static void process(int[] arr, int L,int R){
if(L == R){
return;
}
int mid = L + ((R-L) >> 1);
process(arr, L, mid);
process(arr, mid + 1, R);
merge(arr, L, mid, R);
}
public static void 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;
while (p1 <= M && p2 <= R){
if(arr[p1] < arr[p2])
{
for (int j = 0; j <= (R - p2); j++) {
System.out.println("<" + arr[p1] + "," + arr[p2+j] + ">");
}
}
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];
}
}
public static void main(String[] args) {
int[] arr = new int[]{1,3,4,2,5};
reversePair(arr);
}
}