博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
算法导论部分习题备注
阅读量:4109 次
发布时间:2019-05-25

本文共 1759 字,大约阅读时间需要 5 分钟。

2.4 Inversions

Let A[1...n]be an array of n distinct numbers. If i < j and A[i] > A[j], then thepair(i, j)is called an inversion of A.Give an algorithm that determines the number of inversions in any permutationon n elements in O(nlgn) worst-case time. (Hint: Modify merge sort.)

Thinking: We may think both A[i…j] and A[j+1…k] are sorted subarray of A (0 <= i < j < k <= n). if A[x](i<=x<=j) is bigger than A[j+1], then all numbers behind A[x] are bigger than A[j+1], so there are j-x+1 inversions bigger than A[j+1].

class Solution {public:    int getInversionNumbers(vector
& data, int begin, int end) { if (begin < end - 1) { int middle = (begin + end - 1) / 2; int left = solute(data, begin, middle + 1); int right = solute(data, middle + 1, end); return findAndSort(data, begin, middle + 1, end) + left + right; } return 0; }private: int findAndSort(vector
& data, int start, int middle, int end) { vector
left(data.begin() + start, data.begin() + middle); vector
right(data.begin() + middle, data.begin() + end); int i = 0, j = 0, k = start; int count = 0; while (i < left.size() && j < right.size()) { if (left[i] > right[j]) { // If current item in left bigger than the the current item of right, // then all items after current left item is bigger than the left. count += left.size() - i; data[k++] = right[j++]; } else { data[k++] = left[i++]; } } while (i < left.size()) data[k++] = left[i++]; while (j < right.size()) data[k++] = right[j++]; return count; }};

转载地址:http://unlsi.baihongyu.com/

你可能感兴趣的文章
值得推荐的C/C++框架和库 (真的很强大)
查看>>
Json 解析
查看>>
转:LibCurl HTTP部分详细介绍
查看>>
C++ 制作 json 数据 并 传送给服务端(Server) 的 php
查看>>
C++网络通信库性能大比拼
查看>>
cout 与wcout
查看>>
Windbg 32位版本和64位版本的选择
查看>>
the CDB process terminated
查看>>
Decoda编译方法
查看>>
MySQL表不能修改、删除等操作,卡死、锁死情况的处理办法。
查看>>
SQL查询~ 存在一个表而不在另一个表中的数据
查看>>
mybatis xml中是sql语句报错: Error creating document instance. Cause: org.xml.sax.SAXPa
查看>>
IntelliJ IDEA(2017)安装和破解
查看>>
java.lang.OutOfMemoryError及解决方案
查看>>
搭建 vue 环境
查看>>
Spring Boot+MyBatis使用原生SQL,执行动态自定义SQL语句
查看>>
OutOfMemoryError Direct buffer memory
查看>>
mapper提示Could not autowire. No beans of … type found?
查看>>
UDP主要丢包原因及具体问题分析
查看>>
springboot 下载不了oracle 的jar包
查看>>