zoukankan      html  css  js  c++  java
  • 数组中的逆序对-剑指Offer

    数组中的逆序对

    题目描述

    在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。

    思路

    1. 如果扫描整个数组,每个数字跟后面的数字比较大小,整体的复杂度是O(n^2)
    2. 可以利用归并排序的算法的思想,在排序的同时判断前后两个子序列中存在的逆序对,都是从后往前排,如果前面的数大于后面的数,因为都是已经排好序的所以前面的数一定比后面的数都大,逆序对为后面剩下的元素的数量,然后正常排序;若小于,则这个元素不产生逆序对,正常排序。时间复杂度是O(nlogn)

    代码

    public class Solution {
        public int InversePairs(int [] array) {
            if (array == null || array.length == 0) {
                return 0;
            }
            int[] copy = new int[array.length];
            for (int i = 0; i < array.length; i++) {
                copy[i] = array[i];
            }
            int count = inverseCore(array, copy, 0, array.length - 1);
            return count;
        }
        public int inverseCore(int[] data, int[] copy, int start, int end) {
            if (start == end) {
                copy[start] = data[start];
                return 0;
            }
            int length = (end - start) / 2;
    
            int left = inverseCore(copy, data, start, start + length);
            int right = inverseCore(copy, data, start + length + 1, end);
            int i = start + length;
            int j = end;
            int indexCopy = end;
            int count = 0;
            while (i >= start && j >= start + length + 1) {
                if (data[i] > data[j]) {
                    copy[indexCopy--] = data[i--];
                    count += j - (start + length);
                }
                else {
                    copy[indexCopy--] = data[j--];
                }
    
            }
            for (; i >= start; i--) {
                copy[indexCopy--] = data[i];
            }
            for (; j >= start+length+1; j--) {
                copy[indexCopy--] = data[j];
            }
    
            return count + left + right;
        }
    }
  • 相关阅读:
    ubuntu 12.04 install flash for firefox
    ubuntu 12.04 修改 grub 启动参数
    ubuntu 12.04 英文系统怎么调出 ibus输入法
    Ubuntu 12.04 临时禁用和启动面板
    git部署
    php 递归删除文件夹
    一‘php文件系统
    xml的解构与组装
    memcached的部署
    1,秒杀系统的设计
  • 原文地址:https://www.cnblogs.com/rosending/p/5644986.html
Copyright © 2011-2022 走看看