打印所有包含C ++中元素正负值的对
在这个问题中,我们得到了一个唯一整数数组。并且我们必须返回数组中存在的所有整数对(正整数和负整数)。
让我们举个例子来更好地理解问题-
Input: array = {1 , 4 , 7 , -1, 2, 5, -7}
Output: -11 -33解决问题的一种简单方法是使用两个循环并找到正负对。但是此解决方案将是一个复杂的解决方案,并且时间复杂度约为n2,其中n是数组的大小。
但是,我们必须找到一种更有效的方法来解决问题。为此,我们将首先对数组进行排序。然后在此排序数组中,为每个负整数找到相反的(正)整数。这种二进制搜索将是一个很好的方法。并打印使用搜索找到的对。
示例
让我们看一下该方法的代码说明-
#include <bits/stdc++.h>
using namespace std;
void positiveNegativePair(int arr[], int n) ;
int main(){
int arr[] = { 1, 4, 6 , 3, -1, -2, 5, -6, -5 , 8 };
int n = 10;
cout<<"Postive Negative pairs in the array are :\n";
positiveNegativePair(arr, n);
return 0;
}
void positiveNegativePair(int arr[], int n){
bool pair_exists = false;
sort(arr, arr + n);
for (int i = 0; i < n; i++) {
if (arr[i] < 0) {
if (binary_search(arr, arr + n, -arr[i])) {
cout<<arr[i]<<", "<<-arr[i]<<"\t";
pair_exists = true;
}
}
else
break;
}
if (!pair_exists)
cout << "No positive-negative pairs exist in the code";
}输出结果
数组中的正负对为-
-6, 6 -5, 5 -1, 1
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿