Given two arrays a and b .Find all pairs of elements (a1,b1) such that a1 belongs to Array A and b1 belongs to Array B whose sum a1+b1 = k

前端 未结 5 686
夕颜
夕颜 2020-11-27 16:25

I am looking for the solution of following algorithm with minimal time and space complexity.

Given two arrays a and b, find all pairs of elements (a1,

5条回答
  •  我在风中等你
    2020-11-27 16:44

    I used C++ and it seemed to give me the desired result. Hope this is what you were looking for.

    using namespace std;
    
    using data=std::pair;
    
    void search_pairs(std::vector& A, std::vector& B, const int total, std::vector& output){
    
      std::sort(A.begin(),A.end(),[](const int i,const int j)->bool{return (ibool{return (a* minV(nullptr);
      std::vector* maxV(nullptr);
      if(A.size()>B.size()) {minV=&B;maxV=&A;}
      else {minV=&A;maxV=&B;}
      for(auto&& itr:(*minV) ){
        auto remain(total-itr);
        if (std::binary_search (maxV->begin(), maxV->end(), remain)){
          data d{itr,remain};
          if (minV==&B) std::swap(d.first,d.second);
          output.push_back(d);
        }
      }
      if (minV==&B) std::reverse(output.begin(),output.end());  
    }
    
    int main() {
    
        size_t nb(0);
        scanf("%lu",&nb);
        for (size_t i=0;i A,B;
            for (size_t i=0;i output;
            search_pairs(A, B, total, output);
        auto itr=std::begin(output);
        if (itr==std::end(output)) printf("-1"); 
        while (itr!=std::end(output)){
          printf("%d %d",(*itr).first, (*itr).second);
          if (++itr!=std::end(output)) printf(", ");
        }
            printf("\n");
        }
        //code
        return 0;
    }
    

提交回复
热议问题