题解 | #数组中的逆序对#

数组中的逆序对

https://www.nowcoder.com/practice/96bd6684e04a44eb80e6a68efc0ec6c5

#include <vector>
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param nums int整型vector
     * @return int整型
     */
    const int MOD = 1000000007;
    long long invCount = 0;
    int InversePairs(vector<int>& nums) {
        if (nums.size() < 2) return 0;
        invCount = 0;
        mergeSort(nums, 0, nums.size() - 1);
        return invCount;
    }

    void merge(vector<int>& nums, int left, int mid, int right) {
        //分配左右数组的大小
        int leftSize = mid - left + 1;
        int rightSize = right - mid;

        //声明两个临时数组来存储左边和右边元素
        vector<int> leftArr(leftSize);
        vector<int> rightArr(rightSize);

        //拷贝元素到临时数组
        for (int i = 0; i < leftSize; ++i) {
            leftArr[i] = nums[left + i];
        }
        for (int j = 0; j < rightSize; ++j) {
            rightArr[j] = nums[mid + 1 + j];
        }

        //合并临时数组到原数组
        int i = 0, j = 0, k = left;

        while (i < leftSize && j < rightSize) {
            if (leftArr[i] <= rightArr[j]) {
                nums[k] = leftArr[i];
                i++;
            } else {
                nums[k] = rightArr[j];
                j++;
                invCount += (leftSize - i);
                invCount %= MOD;
            }

            k++;
        }

        //合并剩余的元素
        while (i < leftSize) {
            nums[k] = leftArr[i];
            i++;
            k++;
        }

        while (j < rightSize) {
            nums[k] = rightArr[j];
            j++;
            k++;
        }
    }

    void mergeSort(vector<int>& nums, int left, int right) {

        if (left < right) {
            int mid = left + (right - left) / 2;
            mergeSort(nums, left, mid);
            mergeSort(nums, mid + 1, right);
            merge(nums, left, mid, right);
        }
    }
};

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务