• 逆序对,暴力破解


     public int reversePairs(int[] nums) {
            int cnt = 0;
            int len = nums.length;
            for (int i = 0; i < len - 1; i++) {
                for (int j = i + 1; j < len; j++) {
                    if (nums[i] > nums[j]) {
                        cnt++;
                    }
                }
            }
            return cnt;
        }

    归并方式:

     public int reversePairs(int[] nums) {
            int len = nums.length;
    
            if (len < 2) {
                return 0;
            }
    
            int[] copy = new int[len];
            for (int i = 0; i < len; i++) {
                copy[i] = nums[i];
            }
    
            int[] temp = new int[len];
            return reversePairs(copy, 0, len - 1, temp);
        }
    
        /**
         * nums[left..right] 计算逆序对个数并且排序
         *
         * @param nums
         * @param left
         * @param right
         * @param temp
         * @return
         */
        private int reversePairs(int[] nums, int left, int right, int[] temp) {
            if (left == right) {
                return 0;
            }
    
            int mid = left + (right - left) / 2;
            int leftPairs = reversePairs(nums, left, mid, temp);
            int rightPairs = reversePairs(nums, mid + 1, right, temp);
    
            if (nums[mid] <= nums[mid + 1]) {
                return leftPairs + rightPairs;
            }
    
            int crossPairs = mergeAndCount(nums, left, mid, right, temp);
            return leftPairs + rightPairs + crossPairs;
        }
    
        /**
         * nums[left..mid] 有序,nums[mid + 1..right] 有序
         *
         * @param nums
         * @param left
         * @param mid
         * @param right
         * @param temp
         * @return
         */
        private int mergeAndCount(int[] nums, int left, int mid, int right, int[] temp) {
            for (int i = left; i <= right; i++) {
                temp[i] = nums[i];
            }
    
            int i = left;
            int j = mid + 1;
    
            int count = 0;
            for (int k = left; k <= right; k++) {
    
                if (i == mid + 1) {
                    nums[k] = temp[j];
                    j++;
                } else if (j == right + 1) {
                    nums[k] = temp[i];
                    i++;
                } else if (temp[i] <= temp[j]) {
                    nums[k] = temp[i];
                    i++;
                } else {
                    nums[k] = temp[j];
                    j++;
                    count += (mid - i + 1);
                }
            }
            return count;
        }
  • 相关阅读:
    打印对象的 “精心骗局”
    js继承(自备水,这非常干货)
    递归实现深拷贝( 只要学过js递归,看不懂找我包会 )
    PuTTY SSH 使用证书免密码登录
    git 使用
    php socket通信的简单实现
    基于PHP实现短信验证码接口的方法
    PHP实现页面静态化的简单方法分享
    Yii2使用数据库操作汇总(增删查改、事务)
    PHP 获取当前页面的URL信息
  • 原文地址:https://www.cnblogs.com/zzq-include/p/13583606.html
Copyright © 2020-2023  润新知