划分和征服:IndexSearch

时间:2013-02-15 19:57:01

标签: recurrence divide-and-conquer

我自己解决了以下任务:

给出算法以找到索引i,使得1< = i< = n并且A [i] = i提供这样的索引。如果有任何这样的索引,算法可以返回任何索引。

我使用了分而治之的方法,结果我得到了:

public static int IndexSearch(int []A, int l, int r) {
  if (l>r)
     return -1;
  int m = (l+r)/2;  
  IndexSearch(A, l, m-1); 
  IndexSearch(A, m+1, r);
  if (A[m]==m)
     return m;
  else
     return -1;
}

首先想问一下它是否正确?我想是的....

在这种情况下递归T(n)是什么?

我认为:

2T(n / 2)+ O(1)---->这样对吗?我能详细解释一下如何用主定理来解决复发问题吗?

a = 2 b = 2 f(n)= 1 n ^ logba = n ---> n vs 1所以我们有CASE 1导致O(n) - > ????正确?

2 个答案:

答案 0 :(得分:0)

这肯定是不正确的。

由于您忽略了递归调用的返回值,因此您的程序实际上只检查您第一次调用中是A[m] == m,如果不是这样,则返回-1

“显而易见”的解决方案如下:

public static int IndexSearch(int []A, int l, int r) {
  for i in range(1, length(A))
    if (A[i] == i)
      return i
  return -1
}

这也是一个非常明确的解决方案,所以也许比较复杂的解决方案更受欢迎。

对不起,我无法帮助你处理其他问题。

编辑:这应该有效。它是用Python编写的,但它应该很容易理解。 关于分而治之的问题是将问题减少到解决方案明显的程度。在我们的例子中,那将是只有一个元素的列表。 这里唯一的困难是传回返回值。

def index(l, a, b):
    if a == b: #The basecase, we consider a list with only one element
        if l[a] == a:
            return a
        else: return -1

    #Here we actually break up
    m = (a+b)/2

    i1 = index(l, a, m)
    if i1 != -1:
        return i1

    i2 = index(l, m+1, b)
    if i2 != -1:
        return i2

    return -1

以下是输出示例:

l = [1,2,3,3,5,6,7,8,9]
print index(l, 0, len(l)-1)

Output: 3

希望有所帮助。

编辑:找到所有出现的事实上会带来更好的解决方案:

def index(l, a, b):     
    if a == b:
        if l[a] == a:
            return [a]
        else:
            return []

    m = (a+b)/2
    return index(l, a, m) + index(l, m+1, b)

哪个有输出:

l = [1,2,3,3,5,6,7,8,8]
print "Found " , index(l, 0, len(l)-1), " in " , l

Found  [3, 8]  in  [1, 2, 3, 3, 5, 6, 7, 8, 8]

l = range(0,5)
print "Found " , index(l, 0, len(l)-1), " in " , l

Found  [0, 1, 2, 3, 4]  in  [0, 1, 2, 3, 4]

我认为这是一个很好的,纯粹的解决方案; - )

答案 1 :(得分:0)

我想这可能是一个可能的解决方案,我打印出所有可能的元素,其中value = index。

public static int IndexSearch(int []A, int l, int r) {

 if (l>r)
   return -1;


 //Divide into subproblems
 int m = (l+r)/2;  

 //Conquer and find solution to subproblems recursively
 IndexSearch(A, l, m-1); 
 IndexSearch(A, m+1, r);

 //Combine solutions of subproblems to the orignal solution of the problem 
 if (A[m]==m)
   System.out.println(m);

 return 1;

}

相关问题