代码之家  ›  专栏  ›  技术社区  ›  recipriversexclusion

使用迭代器解决数组求和问题并仅进行等式测试

  •  1
  • recipriversexclusion  · 技术社区  · 15 年前

    在准备面试时,我决定使用迭代器逻辑编写经典的“查找数组中是否有两个元素的总和等于给定的数字”问题,这样就可以将它推广到其他容器而不是其他容器 vector .

    这是我目前的工作

    // Search given container for two elements with given sum. 
    // If two such elements exist, return true and the iterators 
    // pointing to the elements. 
    bool hasElementSum( int sum, const vector<int>& v, vector<int>::iterator& el1, vector<int>::iterator& el2 )
    {
        bool ret = false;
        el1 = v.begin();
        el2 = v.end()-1;
        while ( el1 != el2 ) {
            if ( *el1 + *el2 == sum ) return true;
            ++el1;--el2;
        }
        return false;
    }
    

    while ( el1 >= el2 ) . 我查看的各种源代码都建议不要对迭代器使用omly等式检查,以便能够推广到支持迭代器的所有类型的容器。

    谢谢!

    5 回复  |  直到 15 年前
        1
  •  5
  •   Jerry Coffin    15 年前

    首先,你的算法是错误的 除非

    如果输入没有排序,那么@sbi的答案就和它得到的一样好。

        2
  •  3
  •   sbi    15 年前
    foreach element1 in array
      foreach element2 in array + &element1
        if( element1 + element2 == sum )
          return true
    return false
    

        3
  •  2
  •   Itsik    15 年前

    这个问题通常不是用排序数组问的吗?

        4
  •  0
  •   josh    15 年前

    用向量的所有元素构造一个二叉搜索树,然后对每个元素

    foreach(element = vec.begin to vec.end)
    {
        if element == node.data, skip
    
        if the element + node.data == sum, return true
    
        if the element + node.data > sum, goto left child
    
        if the element + node.data < sum, goto right child
    }
    

        5
  •  0
  •   recipriversexclusion    15 年前

    抱歉,我搞砸了。我想写的是一个排序,然后是一个线性传递,这是对这个问题给出的典型答案,正如ltsik在给Jerry的评论中指出的,比如

    bool hasElementSum( int sum, const vector<int>& v, int* ind1, int* ind2 )
    {
    
        *ind1 = 0; *ind2 = v.size()-1;
    
        std::sort( v.begin(), v.end() );
    
        while ( *ind1 <= *ind2 ) {
            int s = v[*ind1] + v[*ind2];
            if ( s > sum ) (*ind1)++;
            else if ( s < sum ) (*ind2)++;
            else return true
        }
        return false;
    }
    

    while (iter1 <= iter2 )