• 【剑指offer】面试题36:数组中的逆序对


    # @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/

  • 相关阅读:
    博客作业6
    博客作业5
    3137102127 林志坤(实验3)
    3137102127 林志坤(实验2)
    个人简介
    Bookstore项目测试缺陷报告
    自我介绍
    第6次博客园作业
    软件测试第6次作业
    《构建之法》心得体会
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/3938110.html
Copyright © 2020-2023  润新知