小和问题和逆序对问题

Posted dockerchen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了小和问题和逆序对问题相关的知识,希望对你有一定的参考价值。

思路:使用归并排序,每一轮归并后都局部有序,可以利用这个,减少时间复杂度

小和问题

关键代码:

 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;
    

以上是关于小和问题和逆序对问题的主要内容,如果未能解决你的问题,请参考以下文章

算法逆序对问题

剑指offer——数组中的逆序对

每日一题逆序对

每日一题逆序对

每日一题逆序对

算法归并排序 小和 问题