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

原题

在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).

Reference Answer

思路分析

这道题用python如何都会超时,直接转C++好了。

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]);
        return InversePairsCore(copy, data, 0, data.size() - 1)%1000000007;
    }
    long InversePairsCore(vector<int> &data, vector<int> &copy, int begin, int end){
        if(begin == end){
            copy[begin] = data[end];
            return 0;
        }
        
        int length = (end-begin)/2;
        long left = InversePairsCore(copy, data, begin, begin + length);
        long right = InversePairsCore(copy, data, begin + length + 1, end);
        
        int i = begin + length;
        int j = end;
        int indexcopy = end;
        long count = 0;
        
        while(i >= begin && j >= begin+length+1){
            if(data[i] > data[j]){
                copy[indexcopy--] = data[i--];
                count = count + j - begin - length;
            }
            else
                copy[indexcopy--] = data[j--];
        }
        for(;i>= begin; --i)
            copy[indexcopy--] = data[i];
        for(;j>=begin+length+1; --j)
            copy[indexcopy--] = data[j];
        return left + right + count;
        }
};

                

猜你喜欢

转载自blog.csdn.net/Dby_freedom/article/details/84309779