從數(shù)組中找到一對(duì)元素,其和等于給定的數(shù)字給定n個(gè)整數(shù)的數(shù)組,給定一個(gè)數(shù)X,找到所有唯一的元素對(duì)(a,b),其求和等于X。下面是我的解決方案,它是O(nlog(N)+n),但我不確定它是否是最優(yōu)的。int main(void){
int arr [10] = {1,2,3,4,5,6,7,8,9,0};
findpair(arr, 10, 7);}void findpair(int arr[], int len, int sum){
std::sort(arr, arr+len);
int i = 0;
int j = len -1;
while( i < j){
while((arr[i] + arr[j]) <= sum && i < j)
{
if((arr[i] + arr[j]) == sum)
cout << "(" << arr[i] << "," << arr[j] << ")" << endl;
i++;
}
j--;
while((arr[i] + arr[j]) >= sum && i < j)
{
if((arr[i] + arr[j]) == sum)
cout << "(" << arr[i] << "," << arr[j] << ")" << endl;
j--;
}
}}
從數(shù)組中找到一對(duì)元素,其和等于給定的數(shù)字
白豬掌柜的
2019-07-04 12:40:51