从数组中查找总和等于给定数字的一对元素

编程入门 行业动态 更新时间:2024-10-27 18:26:33
本文介绍了从数组中查找总和等于给定数字的一对元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

给定 n 个整数数组和一个数字 X,找出所有唯一的元素对 (a,b),其总和等于 X.

Given array of n integers and given a number X, find all the unique pairs of elements (a,b), whose summation is equal to X.

以下是我的解决方案,是O(nLog(n)+n),但我不确定它是否是最优的.

The following is my solution, it is O(nLog(n)+n), but I am not sure whether or not it is optimal.

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--; } } }

推荐答案

# Let arr be the given array. # And K be the give sum for i=0 to arr.length - 1 do # key is the element and value is its index. hash(arr[i]) = i end-for for i=0 to arr.length - 1 do # if K-th element exists and it's different then we found a pair if hash(K - arr[i]) != i print "pair i , hash(K - arr[i]) has sum K" end-if end-for

更多推荐

从数组中查找总和等于给定数字的一对元素

本文发布于:2023-11-30 12:24:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649937.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:总和   组中   元素   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!