标签:
class Solution { public: int InversePairs(vector<int> data) { if ( data.size() <= 0 ) return 0 ; int length = data.size() ; int retVal ; for ( int i = 0; i < length; i++ ) { int n = data[i] ; for (int j = i + 1; j < length; j++ ) { if ( data[j] < n ) { retVal++ ; } } } return retVal ; } };
// 30.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <vector> using namespace::std; class Solution { public: int InversePairs(vector<int> data) { if (data.size() <= 0) return 0; vector<int> copy; for (int i = 0; i < data.size(); i++){ copy.push_back(data[i]); } int retVal = InversePairsCore(data, copy, 0, data.size() - 1); return retVal; } int InversePairsCore(vector<int>& data, vector<int>& copy, int start, int end) { if (start == end) { copy[start] = data[start]; return 0; } int length = (end - start) / 2; int left = InversePairsCore(copy, data, start, start + length); int right = InversePairsCore(copy, data, start + length + 1, end); int i = start + length; int j = end; int indexOfCopy = end; int count = 0; while (i >= start && j >= start + length + 1) { if (data[i] > data[j]) { copy[indexOfCopy--] = data[i--]; count += j - start - length; } else { copy[indexOfCopy--] = data[j--]; } } for (; i >= start; --i) copy[indexOfCopy--] = data[i]; for (; j >= start + length + 1; --j) copy[indexOfCopy--] = data[j]; return left + right + count; } }; int _tmain(int argc, _TCHAR* argv[]) { vector<int> test; test.push_back(7); test.push_back(5); test.push_back(6); test.push_back(4); Solution s; int result = s.InversePairs(test); return 0; }
标签:
原文地址:http://blog.csdn.net/chengonghao/article/details/51366725