Title: two numbers in the array, if a number is greater than the front behind the figures, the two numbers form a reverse pair. Enter an array, this array P. finds the total number of reverse pair P and outputs the result modulo 1000000007. I.e., the output P% 1000000007
idea: merge sort. First an array is divided into several equal-length sub-array, and then merge sort when subarray and reverse order statistics, the time complexity of merge sort O (nlogn)
Note: The reason for the exchange of data and copy:
. in each operation, and are based on comparing the value of the first term of the current passed to the function, ie data; results of the comparison are stored in the copy; at this time means that the copy is the result of this invocation results .
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's solution:
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