【剑指offer】35.数组中的逆序对

题目

在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007

输入描述:题目保证输入的数组中没有的相同的数字

数据范围:

  1. 对于%50的数据,size<=10^4
  2. 对于%75的数据,size<=10^5
  3. 对于%100的数据,size<=2*10^5

示例1
输入
1,2,3,4,5,6,7,0
输出
7


分析

这道题属于最佳单的思路就是对数组建遍历,找到每个元素之后比自己小的元素个数,但这种思路的时间复杂度为 O ( n 2 ) O(n^2) O(n2),这样的做法不够高效。更加高效思路则是利用归并排序的思路进行求解。主要思路如下:

  1. 把数据分成前后两个数组(递归分到每个数组仅有一个数据项);
  2. 合并数组,合并时,出现前面的数组值array[i]大于后面数组值array[j]时;则前面数组array[i]~array[mid]都是大于array[j]的,count += mid+1 - i

github链接: JZ35-数组中的逆序对


C++代码

#include <iostream>
#include <vector>
using namespace std; 

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

int main()
{
    
    
	int n;
	while(cin>>n){
    
    
		vector<int> ans(n);
		for(int i = 0 ; i < n ; i++){
    
    
			cin>>ans[i];
		}
		Solution s;
		cout<<s.InversePairs(ans);
	}
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_30091945/article/details/107454058