1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
|
class Solution { public: const int MOD = 1000000007;
int InversePairs(vector<int>& nums) { if (nums.size() == 0) return 0; vector<int> copy(nums); return InversePairsCore(nums, copy, 0, nums.size() - 1); }
int InversePairsCore(vector<int>& nums, vector<int>& copy, int begin, int end) { if (begin == end) return 0;
int mid = begin + (end - begin) / 2; int left = InversePairsCore(copy, nums, begin, mid); int right = InversePairsCore(copy, nums, mid + 1, end);
int end1 = mid; int end2 = end; int copyIndex = end; long res = 0; while (begin <= end1 && mid + 1 <= end2) { if (nums[end1] > nums[end2]) { copy[copyIndex --] = nums[end1 --]; res += end2 - mid; res %= MOD; } else { copy[copyIndex --] = nums[end2 --]; } } while (begin <= end1) copy[copyIndex --] = nums[end1 --]; while (mid + 1 <= end2) copy[copyIndex --] = nums[end2 --];
return (left + right + res) % MOD; } };
class Solution { public: const int MOD = 1000000007;
int InversePairs(vector<int>& nums) { if (nums.size() == 0) return 0; vector<int> copy(nums); return InversePairsCore(nums, copy, 0, nums.size() - 1); }
int InversePairsCore(vector<int>& nums, vector<int>& copy, int begin, int end) { if (begin == end) return 0;
int mid = begin + (end - begin) / 2; int low1 = begin, high1 = mid, low2 = mid + 1, high2 = end; int left = InversePairsCore(copy, nums, low1, high1); int right = InversePairsCore(copy, nums, low2, high2);
long res = 0; int copyIndex = low1; while (low1 <= high1 && low2 <= high2) { if (nums[low1] < nums[low2]) { copy[copyIndex ++] = nums[low1 ++]; } else { copy[copyIndex ++] = nums[low2 ++]; res += high1 - low1 + 1; res %= MOD; } } while (low1 <= high1) copy[copyIndex ++] = nums[low1 ++]; while (low2 <= high2) copy[copyIndex ++] = nums[low2 ++];
return (left + right + res) % MOD; } };
|