首页 > 代码库 > 【剑指offer】数组中的逆序对
【剑指offer】数组中的逆序对
# @left part: [start, mid] # @right part: (mid, end] def merge(data, start, mid, end): if mid < start or end < mid: return 0 reverse = 0 ''' @ for start, it play as the start index of left part, and mid @ play as the end index of left part; @ mid + 1 (st2) play as the start index of right part, and end @ play as the end index of right part. ''' #@ start of right part st2 = mid + 1 while start <= mid and st2 <= end: if data[start] > data[st2]: # move data[st2] to start, and data[start, - 1] # move back by 1 data.insert(start, data.pop(st2)) reverse += st2 - start # [start, mid] move back by one, so start = start + 1 # and mid = mid + 1 start += 1 mid += 1 # same as start & mid, move back by 1 st2 += 1 else: # no insert or move, so start = start + 1 start += 1 return reverse def mergeSortWithCount(data, start, end): #just one item or Node, return dirctly if len(data) <= 1 or end <= start: return 0 mid = (start + end) >> 1 #@ reversepair number of left part left = mergeSortWithCount(data, start, mid) # reversepair number of right part right = mergeSortWithCount(data, mid + 1, end) # toal count of reverse pair = left + right + {merger(left, right)} return merge(data, start, mid, end) + left + right
这个题,还可以通过线段树来实现,有兴趣的可以找一些线段树的题练一练。下面的链接是我学习线段树的第一个博客。
http://www.notonlysuccess.com/index.php/segment-tree/
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。