其他的一些利用了分治算法的2

Question:

Find the kth largest element in an unsorted array. Note that it is the kth largest element in
the sorted order, not the kth distinct element.
INPUT: An unsorted array A and k.
OUTPUT: The kth largest element in the unsorted array A.

分析:

记该未排序的数组为A

随机生成一个数X,遍历数组A,将小于X的数放入数组A1中,大于等于X的数放入数组A2中(A1与A2仍为无序数组),获取A1与A2的长度,记为len1与len2,若要查找的第k大的元素,其k大于len1,则要寻找的数肯定在数组A2中,则再在A2中进行如上操作,反之则在A1中进行如上操作,如果,恰巧k=len1,则随机到的这个X即为要寻找的第k大的数

伪代码

 1 Function getKthNumber(A,len,k)
 2 Random x
 3 for i←0 to len do
 4         if A[i]<x then
 5             put in A1
 6         else put in A2
 7         end if
 8 end For
 9 len1←len(A1)
10 len2←len(A2)
11 if k=len1 then
12         return x
13 elseif  k>len1  then
14         k←k-len1
15 getKthNumber(A2,len2,k) 
16 else
17 getKthNumber(A1,len1,k)
18 end If
19 end Function

Question2:

Consider an n-node complete binary tree T, where n = 2d 􀀀 1 for some d. Each node v of
T is labeled with a real number xv. You may assume that the real numbers labeling the nodes
are all distinct. A node v of T is a local minimum if the label xv is less than the label xw for
all nodes w that are joined to v by an edge.
You are given such a complete binary tree T, but the labeling is only speci ed in the following
implicit way: for each node v, you can determine the value xv by probing the node v. Show
how to nd a local minimum of T using only O(log n) probes to the nodes of T.

分析:

从树T的根节点开始,将它的大小与自己的子节点比较,若它最小,则直接返回它,否则,看左右节点哪个小,将它当作子树的顶点,重复以上操作。

伪代码:

1 Function FindMin(T)
2 If  min(get(T.root),get(T.left),get(T.right))==get(t.root)  then
3         Return  T.root
4 Elseif  get(T.left)<get(T.right)  then
5         FindMin(T.left)
6 Else
7         FindMin(T.right)
8 Endif
9 endFunction

 

posted @ 2017-10-26 23:08  Babetterdj  阅读(633)  评论(0编辑  收藏  举报