剑指offer51-AcWing-65. 数组中的逆序对
在数组中的两个数字如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。
输入一个数组,求出这个数组中的逆序对的总数。
样例
输入:[1,2,3,4,5,6,0]
输出:6
思路1:
归并排序的思想,在归并排序的过程中,计算逆序对的个数.用空间换时间的方法,时间复杂度为O(nlogn),空间复杂度为O(n)
C++ code:
class Solution {
public:
int mergeSortCore(vector<int> &nums, vector<int> &sortNums, int start, int end, int length){
int left_index = start + length;
int right_index = end;
int sort_index = end;
int count = 0;
while(left_index >= start && right_index >= start + length + 1){
if(nums[left_index] > nums[right_index]){
sortNums[sort_index--] = nums[left_index--];
count += (right_index - start - length);
}else{
sortNums[sort_index--] = nums[right_index--];
}
}
while(left_index >= start){
sortNums[sort_index--] = nums[left_index--];
}
while(right_index >= start + length + 1){
sortNums[sort_index--] = nums[right_index--];
}
for(int i = start; i <= end; i++){
nums[i] = sortNums[i];
}
return count;
}
int mergeSort(vector<int> &nums, vector<int> &sortNums, int start, int end){
if(start == end){
sortNums[start] = nums[start];
return 0;
}
int length = (end - start) / 2;
int left = mergeSort(nums, sortNums, start, start + length);
int right = mergeSort(nums, sortNums, start + length + 1, end);
int count = mergeSortCore(nums, sortNums, start, end, length);
return left + right + count;
}
int inversePairs(vector<int>& nums) {
int n = nums.size();
if(n == 0){
return 0;
}
vector<int> sortNums(n, 0);
return mergeSort(nums, sortNums, 0, n-1);
}
};
思路2:
暴力求解法,实践复杂度为O(n*n)
C++ code:
class Solution {
public:
int inversePairs(vector<int>& nums) {
int res = 0;
int n = nums.size();
for(int i = 0; i < n; i++){
for(int j = i +1; j < n; j++){
if(nums[i] > nums[j]){
res++;
}
}
}
return res;
}
};