數組中的逆序對(C++牛客網)

參考資料:《劍指offer第二版》

參考網址:https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt

解題思路:

(1)使用歸併排序,具體可參考上面那本書,注意每次交換copy和data,這樣可以避免拷貝從而節約時間

(2)這裏需要注意的是,在牛客網中,下面代碼中的三處取模,一處都不可以少!!!

class Solution {
public:
    int InversePairs(vector<int> data) {
        if(data.size()==0) return 0;
        vector<int> copy(data.begin(),data.end());
	return InversePairsCore(data, copy, 0, data.size()-1)%1000000007;
    }
    int InversePairsCore(vector<int> &data, vector<int> &copy,int begin, int end) {
	if(begin==end) return 0;
	int mid = (end+begin)/2,i = mid,j = end,index=end,count=0;
	int left = InversePairsCore(copy, data,begin, mid);
	int right = InversePairsCore(copy, data,mid+1, end);
		
	while(i>=begin && j>=mid+1) {
	    if(data[i]>data[j]) copy[index--]=data[i--],count = (count+j-mid)%1000000007;
	    else copy[index--]=data[j--];
	}
	while(i>=begin) copy[index--]=data[i--];
	while(j>=mid+1) copy[index--]=data[j--];
	return (left+right+count)%1000000007;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章