牛客网-剑指office-数组中的逆序对

题目:在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007
思路:归并排序。先将数组分为若干个长度相等的子数组,然后在合并子数组的时候进行排序、并统计逆序对,时间复杂度为归并排序的O(nlogn)
注:关于data和copy交换的原因:
.在每次的操作中,数值的比较都是采用当前传入函数中第一项,也就是data;比较的结果都存放到copy中;也就意味着此时copy中是经过此次调用的结果。

class Solution {
public:
	int InversePairs(vector<int> data) {
		if (data.size() <= 0) return 0;
		vector<int> copy(data.size());
		for (int i = 0; i < data.size(); ++i)
			copy[i] = data[i];
		long long count= helper(data, copy, 0, data.size() - 1);
		return count % 1000000007;
	}
	long long  helper(vector<int>& data, vector<int>& copy, int start, int end)
	{
		if (start == end)
		{
			copy[start] = data[start];
			return 0;
		}
		int length = (end - start) / 2;
		long long  left = helper(copy, data, start, start + length);
		long long  right = helper(copy, data, start + length + 1, end);
		int i = start + length;
		int j = end;
		int copypos = end;
		long long  count = 0;
		while (i >= start&&j >= (start + length + 1))
		{
			if (data[i] > data[j])
			{
				copy[copypos--] = data[i--];
				count =count+ j - (start + length);
			}
			else
			{
				copy[copypos--] = data[j--];
			}
		}
		for (; i >= start; --i)
				copy[copypos--] = data[i];
		for (; j >= start + length + 1; --j)
				copy[copypos--] = data[j];
		return count + left + right;
		   

	}
};

python的解法:

class Solution:
    def InversePairs(self, data):
        length = len(data)
        copy = []
        for num in data:
            copy.append(num)
        count = self.helper(data, copy, 0, length-1)
        del copy
        return count % 1000000007

    def helper(self, data, copy, start, end):
        if start == end:
            copy[start] = data[start]
            return 0
        length = int((end - start) / 2)
        left = self.helper(copy, data, start, start+length)
        right = self.helper(copy, data, start+length+1, end)
        i = start + length
        j = end
        copypos = end
        count = 0
        while (i >= start) and (j >= start + length + 1):
            if data[i] > data[j]:
                copy[copypos] = data[i]
                copypos -= 1
                i -= 1
                count += j - start - length
            else:
                copy[copypos] = data[j]
                copypos -= 1
                j -= 1
        while i >= start:
                copy[copypos] = data[i]
                copypos -= 1
                i -= 1
        while j >= start + length+1:
                copy[copypos] = data[j]
                copypos -= 1
                j -= 1
        return left + right + count

猜你喜欢

转载自blog.csdn.net/qq_43387999/article/details/91043206