简体   繁体   中英

Find if there are elements (x,y,z) in unsorted array so that x + y = z

Given an unsorted array A[1...n].Write an algorithm that returns true if there are three elements A[i], A[j], A[k] in A so that A[i]+ A[j] = A[k], otherwise the algorithm must return false (note that may be that A[i] = A[j] and it is legal). Needed time is O(n^2). I come up with an algorithm that works in O(n^2 * log(n)). My algorithm sorts the Array and then for each couple of two elements x,y uses binary search to find whether there is an element x+y. Is there a faster solution that takes O(n^2)?

You could sort the array first - O(nlogn)

Then it boils down to finding two sum for A[k] among the elements A[0] .. A[k-1] for any element A[k]

The two sum for a sorted array can be found in O(n) with two pointer technique like:

boolean searchSum( int k, int[] A ) {
      if ( k > A.length - 1 || k < 2 ) return false;
      i = 0, j = k-1

      while ( i < j ) { 

            if (A[i] + A[j] == A[k]) 
                return true; 
            else if (A[i] + A[j] < A[k]) 
                i++; 
            else
                j--; 
      } 

      return false; 
}

for each k it is O(k-1) and overall the complexity should be O(n^2) .

you could call searchSum like:

boolean myMethod( int[] A ) {

   sort(A);
   for ( int i = A.length - 1; i >= 2; i-- ) {
      if ( searchSum( i, A ) ) {
        return true;
      }
   }

   return false;
}

您可以创建具有O(1)查找的A元素的哈希表,并将其用于搜索x + y。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM