剑指 Offer 51. 数组中的逆序对

剑指 Offer 51. 数组中的逆序对

难度困难

在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。

示例 1:

输入: [7,5,6,4]

输出: 5

限制:

0 <= 数组长度 <= 50000

归并排序

class Solution {

    public int reversePairs(int[] nums) {

            return mergeSort(nums);

        }

        int mergeSort(int[] nums){

            int ans = 0;

            int i,j,k,step=1,len1,len2;

            int[] q = new int[nums.length];

            int[] t;

            while(step

                i = 0;

                j = i+step;

                len1 = i+step

                len2 = j+step

                k = 0;

                while(k

                    while(i

                        if(nums[i]<=nums[j])

                        {

                            q[k++] = nums[i++];

                        }

                        else

                        {

                            ans+=(len1-i);

                            q[k++] = nums[j++];

                        }

                    }

                    while(i

                        q[k++] = nums[i++];

                    while(j

                        q[k++] = nums[j++];

                    i+=step;

                    j = i+step;

                    len1 = i+step

                    len2 = j+step

                }

                step = step << 1;

                t = q;

                q = nums;

                nums = t;

            }

            return ans;

        }

    

}

你可能感兴趣的:(剑指,Offer,算法,java,剑指,Offer,51,数组中的逆序对)