Find 2 numbers in an unsorted array equal to a given sum

前端 未结 18 926
太阳男子
太阳男子 2020-11-29 19:56

We need to find pair of numbers in an array whose sum is equal to a given value.

A = {6,4,5,7,9,1,2}

Sum = 10 Then the pairs are - {6,4} ,

18条回答
  •  长情又很酷
    2020-11-29 20:24

    If you assume that the value M to which the pairs are suppose to sum is constant and that the entries in the array are positive, then you can do this in one pass (O(n) time) using M/2 pointers (O(1) space) as follows. The pointers are labeled P1,P2,...,Pk where k=floor(M/2). Then do something like this

    for (int i=0; i 0)
          print(Pj-1,i); // found a pair
          Pj = 0;
      } else
        if (Pj == 0)
          Pj = (i+1);    // found larger unpaired
        else if (Pj < 0)
          print(Pj-1,i); // found a pair
          Pj = 0;
      }
    }
    

    You can handle repeated entries (e.g. two 6's) by storing the indices as digits in base N, for example. For M/2, you can add the conditional

      if (j == M/2) {
        if (Pj == 0)
          Pj = i+1;      // found unpaired middle
        else
          print(Pj-1,i); // found a pair
          Pj = 0;
      } 
    

    But now you have the problem of putting the pairs together.

提交回复
热议问题