zoukankan      html  css  js  c++  java
  • 493. Reverse Pairs

    // see more at https://www.youtube.com/watch?v=j68OXAMlTM4
    // https://leetcode.com/problems/reverse-pairs/discuss/97268/general-principles-behind-problems-similar-to-reverse-pairs
    // http://www.cnblogs.com/grandyang/p/6657956.html
    
    class Solution {
    public:
        int reversePairs(vector<int>& nums) {
            return reversePairs(nums, 0, nums.size()-1);
        }
        int reversePairs(vector<int>& nums, int begin, int end) {
            if (begin >= end)   return 0;
            int m = begin + (end - begin) / 2;
            int res = reversePairs(nums, begin, m);
            res += reversePairs(nums, m+1, end);
            
            int *p = new int[end-begin+1];
            
            int i = begin, j = m+1;
            while (i <= m && j <= end) {
                if (nums[i] > 2L * nums[j]) {   // avoid overflow
                    res += m - i + 1;
                    j++;
                }
                else {
                    i++;
                }
            }
            
            i = begin; j = m+1; int k = 0;
            while (i <= m && j <= end) {
                if (nums[i] > nums[j])
                    p[k++] = nums[j++];
                else
                    p[k++] = nums[i++];
            }
            while (i <= m)
                p[k++] = nums[i++];
            while (j <= end)
                p[k++] = nums[j++];
            for (int i = begin; i <= end; i++) {
                nums[i] = p[i-begin];
            }
            //sort(nums.begin() + begin, nums.begin() + end+1);
            
            return res;
        }
    };
  • 相关阅读:
    奉上简单的.Net后端开发模板
    C#之委托如此简单
    cordova环境搭建
    Linux实现免密码登录
    RHEL7网络管理NetworkManager和nmcli指令
    RHEL7中配置本地YUM软件源
    RHEL7 网口绑定Network Teaming
    Linux工具之top
    Linux工具之ss
    linux工具之lsof
  • 原文地址:https://www.cnblogs.com/JTechRoad/p/9983941.html
Copyright © 2011-2022 走看看