剑指Offer34 数组中的逆序对

 1 /*************************************************************************
 2     > File Name: 34_InversePairsInArray.c
 3     > Author: Juntaran
 4     > Mail: JuntaranMail@gmail.com
 5     > Created Time: 2016年09月02日 星期五 20时05分05秒
 6  ************************************************************************/
 7 
 8 #include <stdio.h>
 9 #include <malloc.h>
10 
11 int InversePairsCore(int* nums, int* copy, int left, int right)
12 {
13     if (left == right)
14     {
15         copy[left] = copy[right];
16         return 0;
17     }
18     int newlength = (right - left) / 2;
19     
20     // 递归
21     int leftCount  = InversePairsCore(copy, nums, left, left+newlength);
22     int rightCount = InversePairsCore(copy, nums, left+newlength+1, right);
23     
24     // i初始化为前半段最后一个数字下标
25     int i = left + newlength;
26     // j初始化为后半段最后一个数字下标
27     int j = right;
28     
29     int indexCopy = right;
30     int count = 0;
31     
32     while (i>=left && j>=left+newlength+1)
33     {
34         if (nums[i] > nums[j])
35         {
36             copy[indexCopy--] = nums[i--];
37             count += j - left - newlength;
38         }
39         else
40         {
41             copy[indexCopy--] = nums[j--];
42         }
43     }
44     
45     for (i; i >= left; --i)
46         copy[indexCopy--] = nums[i];
47     for (j; j>=left+newlength+1; --j)
48         copy[indexCopy--] = nums[j];
49     
50     return leftCount + rightCount + count;
51 }
52 
53 int InversePairs(int* nums, int length)
54 {
55     if (nums==NULL || length<=0)
56         return -1;
57     
58     int* copy = (int*)malloc(sizeof(int)*length);
59     for (int i = 0; i < length; ++i)
60         copy[i] = nums[i];
61     
62     int count = InversePairsCore(nums, copy, 0, length-1);
63     delete[] copy;
64     
65     return count;
66 }
67 
68 int main()
69 {
70     int nums[] = {7,5,6,4};
71     int length = 4;
72     int ret = InversePairs(nums, length);
73     printf("%d\n", ret);
74 }

 

转载于:https://www.cnblogs.com/Juntaran/p/5835668.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值