求逆序对
class Solution { public: int result = 0; int InversePairs(vector<int> data) { int len = data.size(); vector<int> temp(len); MergeSort(data, temp, 0, len-1); return result; } void MergeSort(vector<int>& data, vector<int>& temp, int begin, int end) { if (begin < end) { int mid = (end - begin) / 2 + begin; MergeSort(data, temp, begin, mid); MergeSort(data, temp, mid+1, end); MergeArray(data, temp, begin, mid, end); } } void MergeArray(vector<int>& data, vector<int>& temp, int begin, int mid, int end) { int i = begin; int j = mid + 1; int k = 0; while (i <= mid && j <= end) { if (data[i] < data[j]) { temp[k++] = data[i++]; } // 若左半部分当前元素大于右半部分当前元素 // 则左半部分当前元素后面的每个值都大于它 else { result += (mid - i + 1); result %= 1000000007; temp[k++] = data[j++]; } } while (i <= mid) { temp[k++] = data[i++]; } while (j <= end) { temp[k++] = data[j++]; } for (i = 0; i < k; i++) { data[begin+i] = temp[i]; } } };