程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> Find zero pairs

Find zero pairs

編輯:C++入門知識

Question : Design and implement an algorithm (C++ function) that, given an array of integers, determines whether the sum of any two distinct elements is zero. Assume, of course, that there might be positive and negative values in the array (i.e. don't just look for a pair of zeroes!).   test IDE: Microsoft Visual Studio 2005     test OS:Microsoft Windows 7   The code as following may solve this problem:     [cpp]   #include "stdafx.h"    #include <iostream>    #include <algorithm>    void FindZeroPairs(int data[], int nLen)   {       int pLeft = 0;       int pRight = nLen - 1;       while (pLeft < pRight)       {           if (0 == data[pLeft] + data[pRight])           {   www.2cto.com             printf("Zero pair: %d and %d\n", data[pLeft], data[pRight]);               --pRight;               ++pLeft;               continue;           }           if (0 < data[pLeft] + data[pRight])           {               --pRight;               continue;           }           if (0 > data[pLeft] + data[pRight])           {               ++pLeft;           }       }   }         int _tmain(int argc, _TCHAR* argv[])   {       int nLen;       printf("Input length of integer array:");       scanf("%d", &nLen);       // allocate space for array with length of nLen        int *pData = new int[nLen];       int i = 0;       while (i < nLen)       {           scanf("%d", &pData[i]);           ++i;       }       // sort array        std::sort(pData, pData + nLen);       for (int i = 0; i < nLen; ++i)       {           printf("%d ", pData[i]);       }       printf("\n");          FindZeroPairs(pData, nLen);       return 0;   }     #include "stdafx.h" #include <iostream> #include <algorithm> void FindZeroPairs(int data[], int nLen) { int pLeft = 0; int pRight = nLen - 1; while (pLeft < pRight) { if (0 == data[pLeft] + data[pRight]) { printf("Zero pair: %d and %d\n", data[pLeft], data[pRight]); --pRight; ++pLeft; continue; } if (0 < data[pLeft] + data[pRight]) { --pRight; continue; } if (0 > data[pLeft] + data[pRight]) { ++pLeft; } } }     int _tmain(int argc, _TCHAR* argv[]) { int nLen; printf("Input length of integer array:"); scanf("%d", &nLen); // allocate space for array with length of nLen int *pData = new int[nLen]; int i = 0; while (i < nLen) { scanf("%d", &pData[i]); ++i; } // sort array std::sort(pData, pData + nLen); for (int i = 0; i < nLen; ++i) { printf("%d ", pData[i]); } printf("\n");   FindZeroPairs(pData, nLen); return 0; }        

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved