주어진 제품과 쌍을 확인하십시오

주어진 제품과 쌍을 확인하십시오
GFG 연습에서 시도하십시오

배열이 주어졌습니다 ARR [] ~의 N 뚜렷한 정수와 a 목표 가치 값 작업은 제품이 대상과 동일한 배열에 한 쌍의 요소가 있는지 확인하는 것입니다.

예 :  

입력: ARR [] = [1 5 7-1 5] 대상 = 35
산출: 진실
설명: 5* 7 = 35로 대답은 사실입니다.

입력: ARR [] = [-10 20 9-40] 대상 = 30
산출: 거짓
설명: 제품 30에는 쌍이 없습니다

내용 테이블

[순진한 접근] 가능한 모든 쌍을 생성하여 -O (n 2 ) 시간 및 O (1) 공간

매우 기본적인 접근 방식은 가능한 모든 쌍을 생성하고 제품이 주어진 대상 값과 같은 쌍이 존재하는지 확인하는 것입니다. 진실 . 그러한 쌍이 존재하지 않으면 돌아옵니다 거짓 .

C++
   #include          using     namespace     std  ;   // Function to check if any pair exists whose product   // equals the target   bool     isProduct  (  vector   <  int  >     &  arr       long     long     target  )     {      int     n     =     arr  .  size  ();      for     (  int     i     =     0  ;     i      <     n     -     1  ;     i  ++  )     {      for     (  int     j     =     i     +     1  ;     j      <     n  ;     j  ++  )     {      if     (  1L  L     *     arr  [  i  ]     *     arr  [  j  ]     ==     target  )     {      return     true  ;      }      }      }      return     false  ;   }   int     main  ()     {      vector   <  int  >     arr     =     {  1       5       7       -1       5  };      long     long     target     =     35  ;      cout      < <     isProduct  (  arr       target  )      < <     endl  ;      return     0  ;   }   
C
   #include         #include         // Function to check if any pair exists whose product   // equals the target   bool     isProduct  (  int     arr  []     int     n       long     long     target  )     {      for     (  int     i     =     0  ;     i      <     n     -     1  ;     i  ++  )     {      for     (  int     j     =     i     +     1  ;     j      <     n  ;     j  ++  )     {      if     (  1L  L     *     arr  [  i  ]     *     arr  [  j  ]     ==     target  )     {      return     true  ;      }      }      }      return     false  ;   }   int     main  ()     {      int     arr  []     =     {  1       5       7       -1       5  };      long     long     target     =     35  ;         int     n     =     sizeof  (  arr  )     /     sizeof  (  arr  [  0  ]);      printf  (  '%d  n  '       isProduct  (  arr       n       target  ));          return     0  ;   }   
Java
   class   GfG     {      // Function to check if any pair exists whose product      // equals the target      static     boolean     isProduct  (  int  []     arr       long     target  )     {      int     n     =     arr  .  length  ;      for     (  int     i     =     0  ;     i      <     n     -     1  ;     i  ++  )     {      for     (  int     j     =     i     +     1  ;     j      <     n  ;     j  ++  )     {      if     ((  long  )     arr  [  i  ]     *     arr  [  j  ]     ==     target  )     {      return     true  ;      }      }      }      return     false  ;      }      public     static     void     main  (  String  []     args  )     {      int  []     arr     =     {  1       5       7       -  1       5  };      long     target     =     35  ;         System  .  out  .  println  (  isProduct  (  arr       target  ));      }   }   
Python
   # Function to check if any pair exists whose product   # equals the target   def   is_product  (  arr     target  ):   n   =   len  (  arr  )   for   i   in   range  (  n   -   1  ):   for   j   in   range  (  i   +   1     n  ):   if   arr  [  i  ]   *   arr  [  j  ]   ==   target  :   return   True   return   False   arr   =   [  1     5     7     -  1     5  ]   target   =   35   print  (  is_product  (  arr     target  ))   
C#
   using     System  ;   class     GfG     {      // Function to check if any pair exists whose product      // equals the target      static     bool     IsProduct  (  int  []     arr       long     target  )     {      int     n     =     arr  .  Length  ;      for     (  int     i     =     0  ;     i      <     n     -     1  ;     i  ++  )     {      for     (  int     j     =     i     +     1  ;     j      <     n  ;     j  ++  )     {      if     ((  long  )  arr  [  i  ]     *     arr  [  j  ]     ==     target  )     {      return     true  ;      }      }      }      return     false  ;      }      static     void     Main  ()     {      int  []     arr     =     {     1       5       7       -  1       5     };      long     target     =     35  ;         Console  .  WriteLine  (  IsProduct  (  arr       target  ));      }   }   
JavaScript
   // Function to check if any pair exists whose product   // equals the target   function     isProduct  (  arr       target  )     {      let     n     =     arr  .  length  ;      for     (  let     i     =     0  ;     i      <     n     -     1  ;     i  ++  )     {      for     (  let     j     =     i     +     1  ;     j      <     n  ;     j  ++  )     {      if     (  arr  [  i  ]     *     arr  [  j  ]     ===     target  )     {      return     true  ;      }      }      }      return     false  ;   }   let     arr     =     [  1       5       7       -  1       5  ];   let     target     =     35  ;   console  .  log  (  isProduct  (  arr       target  ));   

산출
1  

시간 복잡성 : 두 개의 중첩 루프를 사용하기위한 O (n²)
보조 공간 : o (1)

[더 나은 접근] 두 개의 포인터 기술 사용 -O (N log (N)) 시간 및 O (1) 공간

이 문제에 대해서도 2 포인터 기술을 사용할 수 있지만 정렬 된 데이터에만 적용됩니다. 먼저 배열을 정렬하고 처음에 두 개의 포인터 하나를 보관하십시오 ( 왼쪽 ) 그리고 끝에 다른 사람 ( 오른쪽 배열의). 그런 다음이 두 포인터에서 요소의 제품을 확인하십시오.

  • 제품이 목표 우리는 쌍을 찾았습니다.
  • 제품이 그보다 적은 경우 목표 움직입니다 왼쪽 에 대한 포인터 오른쪽 제품을 늘리려면.
  • 제품이 더 큰 경우 목표 움직입니다 오른쪽 에 대한 포인터 왼쪽 제품을 줄이기 위해.
C++
   #include          using     namespace     std  ;   // Function to check if any pair exists whose product equals the target.   bool     isProduct  (  vector   <  int  >     &  arr       long     long     target  )     {          // Sort the array      sort  (  arr  .  begin  ()     arr  .  end  ());      int     left     =     0       right     =     arr  .  size  ()     -     1  ;      while     (  left      <     right  )     {      // Calculate the current product      long     long     currProd     =     1L  L  *  arr  [  left  ]  *  arr  [  right  ];      // If the product matches the target return true.      if     (  currProd     ==     target  )     return     true  ;      // Move the pointers based on comparison with target.      if     (  currProd     >     target  )     right  --  ;      else     left  ++  ;      }      return     false  ;   }   int     main  ()     {      vector   <  int  >     arr     =     {  1       5       7       -1       5  };      long     long     target     =     35  ;      cout      < <     isProduct  (  arr       target  )      < <     endl  ;      return     0  ;   }   
C
   #include         #include         #include         // Function to compare two integers (used in qsort)   int     compare  (  const     void     *  a       const     void     *  b  )   {      return     (  *  (  int     *  )  a     -     *  (  int     *  )  b  );   }   // Function to check if any pair exists whose product   // equals the target.   bool     isProduct  (  int     arr  []     int     n       long     long     target  )   {      // Sort the array      qsort  (  arr       n       sizeof  (  int  )     compare  );      int     left     =     0       right     =     n     -     1  ;      while     (  left      <     right  )      {      // Calculate the current product      long     long     currProd     =     (  long     long  )  arr  [  left  ]     *     arr  [  right  ];      // If the product matches the target return true.      if     (  currProd     ==     target  )      return     true  ;      // Move the pointers based on comparison with target.      if     (  currProd     >     target  )      right  --  ;      else      left  ++  ;      }      return     false  ;   }   int     main  ()   {      int     arr  []     =     {  1       5       7       -1       5  };      long     long     target     =     35  ;      int     n     =     sizeof  (  arr  )     /     sizeof  (  arr  [  0  ]);      printf  (  '%d  n  '       isProduct  (  arr       n       target  ));      return     0  ;   }   
Java
   import     java.util.Arrays  ;   class   GfG     {      // Function to check if any pair exists whose product equals the target.      static     boolean     isProduct  (  int  []     arr       long     target  )     {      // Sort the array      Arrays  .  sort  (  arr  );      int     left     =     0       right     =     arr  .  length     -     1  ;      while     (  left      <     right  )     {          // Calculate the current product      long     currProd     =     (  long  )     arr  [  left  ]     *     arr  [  right  ]  ;      // If the product matches the target return true.      if     (  currProd     ==     target  )     return     true  ;      // Move the pointers based on comparison with target.      if     (  currProd     >     target  )     right  --  ;      else     left  ++  ;      }      return     false  ;      }      public     static     void     main  (  String  []     args  )     {      int  []     arr     =     {  1       5       7       -  1       5  };      long     target     =     35  ;         System  .  out  .  println  (  isProduct  (  arr       target  ));      }   }   
Python
   # Function to check if any pair exists whose product equals the target.   def   isProduct  (  arr     target  ):   # Sort the array   arr  .  sort  ()   left     right   =   0     len  (  arr  )   -   1   while   left    <   right  :   # Calculate the current product   currProd   =   arr  [  left  ]   *   arr  [  right  ]   # If the product matches the target return True.   if   currProd   ==   target  :   return   True   # Move the pointers based on comparison with target.   if   currProd   >   target  :   right   -=   1   else  :   left   +=   1   return   False   if   __name__   ==   '__main__'  :   arr   =   [  1     5     7     -  1     5  ]   target   =   35   print  (  isProduct  (  arr     target  ))   
C#
   using     System  ;   using     System.Linq  ;   class     GfG     {      // Function to check if any pair exists whose product      // equals the target.      static     bool     isProduct  (  int  []     arr       long     target  )     {          // Sort the array      Array  .  Sort  (  arr  );      int     left     =     0       right     =     arr  .  Length     -     1  ;      while     (  left      <     right  )     {      // Calculate the current product      long     currProd     =     (  long  )     arr  [  left  ]     *     arr  [  right  ];      // If the product matches the target return true.      if     (  currProd     ==     target  )     return     true  ;      // Move the pointers based on comparison with target.      if     (  currProd     >     target  )     right  --  ;      else     left  ++  ;      }      return     false  ;      }      static     void     Main  (  string  []     args  )     {      int  []     arr     =     {     1       5       7       -  1       5     };      long     target     =     35  ;         Console  .  WriteLine  (  isProduct  (  arr       target  ));      }   }   
JavaScript
   // Function to check if any pair exists whose product   // equals the target.   function     isProduct  (  arr       target  )     {      // Sort the array      arr  .  sort  ((  a       b  )     =>     a     -     b  );      let     left     =     0       right     =     arr  .  length     -     1  ;      while     (  left      <     right  )     {      // Calculate the current product      let     currProd     =     arr  [  left  ]     *     arr  [  right  ];      // If the product matches the target return true.      if     (  currProd     ===     target  )     return     true  ;      // Move the pointers based on comparison with target.      if     (  currProd     >     target  )     right  --  ;      else     left  ++  ;      }      return     false  ;   }   let     arr     =     [  1       5       7       -  1       5  ];   let     target     =     35  ;   console  .  log  (  isProduct  (  arr       target  ));   

산출
1  

시간 복잡성 : 배열을 정렬하기위한 o (n log (n))
보조 공간 : o (1)

[예상 접근] 해시 세트 사용 -O (N) 시간 및 O (N) 공간

우리는 사용할 수 있습니다 해시 세트 효율적으로 찾아보십시오. 배열을 반복 할 때 각 숫자가 대상의 요인인지 확인합니다. 그렇다면 해당 요소가 이미 세트에 있는지 확인합니다. 그렇다면 우리는 돌아옵니다 진실 ; 그렇지 않으면 현재 번호를 세트에 추가하고 계속합니다.

C++
   #include          #include         #include         using     namespace     std  ;   // Function to check if any pair exists whose product   // equals the target.   bool     isProduct  (  vector   <  int  >     &  arr       long     long     target  )     {          // Use an unordered set to store previously seen numbers.      unordered_set   <  int  >     st  ;      for     (  int     num     :     arr  )     {      // If target is 0 and current number is 0 return true.      if     (  target     ==     0     &&     num     ==     0  )     return     true  ;      // Check if current number can be a factor of the target.      if     (  target     %     num     ==     0  )     {      int     secondNum     =     target     /     num  ;          // If the secondNum has been seen before return true.      if     (  st  .  find  (  secondNum  )     !=     st  .  end  ())     {      return     true  ;      }          // Mark the current number as seen.      st  .  insert  (  num  );      }      }      return     false  ;   }   int     main  ()     {      vector   <  int  >     arr     =     {  1       5       7       -1       5  };      long     long     target     =     35  ;      cout      < <     isProduct  (  arr       target  )      < <     endl  ;      return     0  ;   }   
Java
   import     java.util.HashSet  ;   class   GfG     {      // Function to check if any pair exists whose product      // equals the target.      static     boolean     isProduct  (  int  []     arr       long     target  )      {      // Use a hash set to store previously seen numbers.      HashSet   <  Integer  >     set     =     new     HashSet   <>  ();      for     (  int     num     :     arr  )     {      // If target is 0 and current number is 0      // return true.      if     (  target     ==     0     &&     num     ==     0  )      return     true  ;      // Check if current number can be a factor of      // the target.      if     (  target     %     num     ==     0  )     {      int     secondNum     =     (  int  )(  target     /     num  );      // If the secondNum has been seen before      // return true.      if     (  set  .  contains  (  secondNum  ))      return     true  ;      // Mark the current number as seen.      set  .  add  (  num  );      }      }      return     false  ;      }      public     static     void     main  (  String  []     args  )      {      int  []     arr     =     {     1       5       7       -  1       5     };      long     target     =     35  ;      System  .  out  .  println  (  isProduct  (  arr       target  ));      }   }   
Python
   # Function to check if any pair exists whose product equals the target.   def   isProduct  (  arr     target  ):   # Use a set to store previously seen numbers.   st   =   set  ()   for   num   in   arr  :   # If target is 0 and current number is 0 return True.   if   target   ==   0   and   num   ==   0  :   return   True   # Check if current number can be a factor of the target.   if   target   %   num   ==   0  :   secondNum   =   target   //   num   # If the secondNum has been seen before return True.   if   secondNum   in   st  :   return   True   # Mark the current number as seen.   st  .  add  (  num  )   return   False   if   __name__   ==   '__main__'  :   arr   =   [  1     5     7     -  1     5  ]   target   =   35   print  (  isProduct  (  arr     target  ))   
C#
   using     System  ;   using     System.Collections.Generic  ;   class     GfG     {      // Function to check if any pair exists whose product      // equals the target.      static     bool     isProduct  (  int  []     arr       long     target  )      {      // Use a hash set to store previously seen numbers.      HashSet   <  int  >     set     =     new     HashSet   <  int  >  ();      foreach  (  int     num     in     arr  )      {      // If target is 0 and current number is 0      // return true.      if     (  target     ==     0     &&     num     ==     0  )      return     true  ;      // Check if current number can be a factor of      // the target.      if     (  target     %     num     ==     0  )     {      int     secondNum     =     (  int  )(  target     /     num  );      // If the secondNum has been seen before      // return true.      if     (  set  .  Contains  (  secondNum  ))      return     true  ;      // Mark the current number as seen.      set  .  Add  (  num  );      }      }      return     false  ;      }      static     void     Main  (  string  []     args  )      {      int  []     arr     =     {     1       5       7       -  1       5     };      long     target     =     35  ;      Console  .  WriteLine  (  isProduct  (  arr       target  ));      }   }   
JavaScript
   // Function to check if any pair exists whose product equals   // the target.   function     isProduct  (  arr       target  )   {      // Use a set to store previously seen numbers.      let     seen     =     new     Set  ();      for     (  let     num     of     arr  )     {      // If target is 0 and current number is 0 return      // true.      if     (  target     ===     0     &&     num     ===     0  )      return     true  ;      // Check if current number can be a factor of the      // target.      if     (  target     %     num     ===     0  )     {      let     secondNum     =     target     /     num  ;      // If the secondNum has been seen before return      // true.      if     (  seen  .  has  (  secondNum  ))      return     true  ;      // Mark the current number as seen.      seen  .  add  (  num  );      }      }      return     false  ;   }   let     arr     =     [     1       5       7       -  1       5     ];   let     target     =     35  ;   console  .  log  (  isProduct  (  arr       target  ));   

산출
1  

시간 복잡성 : O (n) 단일 반복
보조 공간 : O (n) 해시 세트에 요소를 저장하는 경우