Find all pairs of integers within an array which sum to a specified value

前端 未结 15 2020
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 08:00

Design an algorithm to find all pairs of integers within an array which sum to a specified value.

I have tried this problem using a hash

15条回答
  •  情歌与酒
    2020-12-01 08:41

    #include 
    using namespace std;
    
    #define MAX 15
    
    int main()
    {
     int array[MAX] = {-12,-6,-4,-2,0,1,2,4,6,7,8,12,13,20,24};
     const int find_sum = 0;
     int max_index = MAX - 1;
     int min_index = 0;
     while(min_index < max_index)
     {
      if(array[min_index] + array[max_index-min_index] == find_sum)
      {
       cout << array[min_index] << " & " << array[max_index-min_index] << " Matched" << endl;
       return 0;
      }
      if(array[min_index]+array[max_index-min_index] < find_sum)
      {
       min_index++;
       //max_index++;
      }
      if(array[min_index]+array[max_index-min_index] > find_sum)
      {
       max_index--;
      }
     }
     cout << "NO MATCH" << endl;
     return 0;
    }
    //-12 & 12 matched
    

提交回复
热议问题