F_G

许多问题需要说清楚就可以&&走永远比跑来的重要

导航

[剑指offer] 数组中的逆序对

[剑指offer] 数组中的逆序对 p206

比较暴力的方法,是两两进行比较,统计出现的逆序对的个数,这样时间复杂度是O(N^2)

使用一种类似归并的方法,可以将复杂度降低到O(NlogN)

对于当前数组我们将其分为相等的两部分,对两部分进行递归的操作,知道遇到的子段当中有一个元素或者零个元素,则算法返回。

对递归返回的两部分进行merge

left和right分别指向左右两部分的最后一个index,如果num[left]>right[i]则说明当前出现了逆序对,由于left和right都是从最大值开始进行比较,此时num[left]>num[right]说明 num[left+1],num[left+1],...,num[leftend]都应该是大于num[right]的所以当前逆序对对数增加leftend - left + 1个。

这样在进行merge的过程当中统计可能的逆序数,当排序完毕,则统计完毕,算法复杂度是O(NlogN)

 

int count =0;

reverse-Rank-num(int [] num,int []copy,int left,int right):

  if(left>=right) return;

  int mid = (left+right)/2;

  reverse-Rank-num(num,copy,left,mid);

  reverse-Rank-num(num,copy,mid+1,right);

  int leftindex = mid;

  int rightindex = right;

  int copyindex = right;

  while(leftindex>=left&&rightindex>=mid+1):

    if(num[leftindex]>num[rightindex]):

      copy[copyindex--]=num[rightindex--];

      count = count + leftindex - mid + 1;

    else:

      copy[copyindex+1] = num[leftindex--];

  while(leftindex>=left):

    copy[copyindex--]=num[leftindex--];

  while(rightindex>=mid+1):

    copy[copyindex--]=num[rightindex--];

  return;

posted on 2015-09-06 14:29  F_G  阅读(118)  评论(0编辑  收藏  举报